package cn.stylefeng.guns.modular.demo.controller;


import cn.hutool.core.util.RandomUtil;
import cn.stylefeng.guns.core.exception.BusinessException;
import cn.stylefeng.guns.core.exception.BusinessExceptionEnum;
import cn.stylefeng.guns.dao.*;
import cn.stylefeng.guns.dao.entity.SaleStockStatisticsVO;
import cn.stylefeng.guns.dao.entity.*;
import cn.stylefeng.guns.dao.entity.yaode.GaiaProductBusiness;
import cn.stylefeng.guns.dao.entity.yaode.GaiaSdSaleD;
import cn.stylefeng.guns.dao.entity.yaode.GaiaUserData;
import cn.stylefeng.guns.dao.mapper.GaiaSdSaleHMapper;
import cn.stylefeng.guns.dao.mapper.GaiaSdSalePayMsgMapper;
import cn.stylefeng.guns.dao.mapper.GaiaStoreDataMapper;
import cn.stylefeng.guns.dao.mapper.yaode.GaiaSdSaleDMapper;
import cn.stylefeng.guns.dao.mapper.yaode.GaiaUserDataMapper;
import cn.stylefeng.guns.dao.service.*;
import cn.stylefeng.guns.modular.demo.controller.convert.SaleStockConverter;
import cn.stylefeng.guns.modular.demo.controller.domain.*;
import cn.stylefeng.guns.modular.demo.enums.AuthDataEnums;
import cn.stylefeng.guns.modular.demo.enums.Contants;
import cn.stylefeng.guns.modular.demo.enums.SaleStockTypeEnum;
import cn.stylefeng.guns.modular.demo.excel.domain.*;
import cn.stylefeng.guns.modular.demo.excel.domain.asilikang.APostsSaleExcelVO;
import cn.stylefeng.guns.modular.demo.excel.domain.asilikang.Year23SaleExcelVO;
import cn.stylefeng.guns.modular.demo.excel.listener.StockListener;
import cn.stylefeng.guns.modular.demo.excel.listener.aslikang.StockAsPosSaleListener;
import cn.stylefeng.guns.modular.demo.service.SaleStockBizService;
import cn.stylefeng.guns.util.FileUtil;
import cn.stylefeng.guns.util.RebateDateUtil;
import cn.stylefeng.roses.kernel.auth.api.context.LoginContext;
import cn.stylefeng.roses.kernel.auth.api.pojo.login.LoginUser;
import cn.stylefeng.roses.kernel.auth.api.pojo.login.basic.SimpleRoleInfo;
import cn.stylefeng.roses.kernel.config.api.context.ConfigContext;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.rule.annotation.BusinessLog;
import cn.stylefeng.roses.kernel.rule.enums.ResBizTypeEnum;
import cn.stylefeng.roses.kernel.rule.pojo.response.ResponseData;
import cn.stylefeng.roses.kernel.rule.pojo.response.SuccessResponseData;
import cn.stylefeng.roses.kernel.scanner.api.annotation.ApiResource;
import cn.stylefeng.roses.kernel.scanner.api.annotation.GetResource;
import cn.stylefeng.roses.kernel.scanner.api.annotation.PostResource;
import cn.stylefeng.roses.kernel.system.api.UserServiceApi;
import cn.stylefeng.roses.kernel.system.modular.user.entity.SysUser;
import cn.stylefeng.roses.kernel.system.modular.user.service.SysUserRoleService;
import cn.stylefeng.roses.kernel.system.modular.user.service.SysUserService;
import cn.stylefeng.roses.kernel.system.modular.user.service.impl.SysUserAdminServiceImpl;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.*;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

import static cn.stylefeng.guns.modular.demo.service.SyncService.SIMPLE_DATE_FORMAT1;
import static cn.stylefeng.guns.modular.demo.service.SyncService.SIMPLE_DATE_FORMAT2;

@RestController
@ApiResource(name = "进销存", resBizType = ResBizTypeEnum.BUSINESS, path = "/stock")
@Slf4j
public class SaleStockController {

    @Resource
    private ISupplierService supplierService;

    @Resource
    private ISaleStockService saleStockService;
    @Resource
    private IRuleSupplierService ruleSupplierService;
    @Resource
    private SaleStockConverter saleStockConverter;
    @Resource
    private IGoodsService goodsService;
    @Resource
    private IUserExtendService userExtendService;

    @Resource
    private IStoreService storeService;
    @Resource
    private IGaiaSdSalePayMsgService gaiaSdSalePayMsgService;
    @Resource
    private IGaiaProductBusinessService gaiaProductBusinessService;
    @Resource
    private IUserRelationService userRelationService;
    @Resource
    private SysUserRoleService sysUserRoleService;

    @Resource
    private IGaiaWmsKucenService gaiaWmsKucenService;
    @Resource
    private IWholesaleSalesRecordService wholesaleSalesRecordService;
    @Resource
    private IGaiaBatchInfoService gaiaBatchInfoService;

    @Resource
    private SaleStockBizService saleStockBizService;
    @Autowired
    private ISalesStockBatchService salesStockBatchService;
    @Resource
    private GaiaSdSaleDMapper gaiaSdSaleDMapper;
    @Resource
    private GaiaUserDataMapper gaiaUserDataMapper;
    @Resource
    private IGaiaWmsDiaoboZService gaiaWmsDiaoboZService;
    @Resource
    private GaiaStoreDataMapper gaiaStoreDataMapper;
    @Resource
    private ITestBillDetailService testBillDetailService;
    @Resource
    private GaiaSdSalePayMsgMapper gaiaSdSalePayMsgMapper;
    @Autowired
    private SysUserAdminServiceImpl sysUserAdminServiceImpl;
    @Resource
    private UserServiceApi userServiceApi;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private GaiaSdSaleHMapper gaiaSdSaleHMapper;
    @Resource
    private ISaleStockImportTimeService saleStockImportTimeService;


    @PostResource(name = "进销存统计数据", path = "/stock/statistics", requiredLogin = true, requiredPermission = true)
    @ApiOperation("进销存统计数据")
    public ResponseData<StatisticsSaleStockVO> statisticsStockList(@RequestBody StatisticsSaleStockRequest statisticsSaleStockRequest) {

        StatisticsSaleStockVO statisticsSaleStockVO = saleStockBizService.getStatisticsSaleStockVO(statisticsSaleStockRequest);

        return new SuccessResponseData<>(statisticsSaleStockVO);
    }

    @PostResource(name = "进销存统计数据根据时间统计", path = "/stock/statistics/time", requiredLogin = true, requiredPermission = true)
    @ApiOperation("进销存统计数据根据时间统计")
    public ResponseData<StatisticsSaleStockVO> statisticsStockListByTime(@RequestBody StatisticsSaleStockRequest saleStockRequest) {

        StatisticsSaleStockVO statisticsSaleStockVO = saleStockBizService.getStatisticsSaleStockVOByTime(saleStockRequest);


        return new SuccessResponseData<>(statisticsSaleStockVO);
    }

    @PostResource(name = "进销存期初期末统计", path = "/stock/statistics/v3", requiredLogin = true, requiredPermission = true)
    @ApiOperation("进销存统计数据根据时间统计")
    public ResponseData<IPage<SaleStockStatisticsVO>> statisticsStockListByTimeV3(@RequestBody StatisticsSaleStockV3Request saleStockC3Request) {

        IPage<SaleStockStatisticsVO> statisticsStatisticsSaleStockV3Request = saleStockBizService.getStatisticsStatisticsSaleStockV3Request(saleStockC3Request);

        return new SuccessResponseData<>(statisticsStatisticsSaleStockV3Request);
    }

    @PostResource(name = "进销存期初期末统计", path = "/stock/statistics/total", requiredLogin = true, requiredPermission = true)
    @ApiOperation("进销存统计数据根据时间统计")
    public ResponseData<SaleStockStatisticsVO> statisticsStockListByTimeTotal(@RequestBody StatisticsSaleStockV3Request saleStockC3Request) {

        SaleStockStatisticsVO statisticsStatisticsSaleStockTotalRequest = saleStockBizService.getStatisticsStatisticsSaleStockTotalRequest(saleStockC3Request);

        return new SuccessResponseData<>(statisticsStatisticsSaleStockTotalRequest);
    }

    /**
     * 采购数量
     *
     * @param batchNo
     * @return
     */
    private Integer getPurchaseAmount(String batchNo) {
        QueryWrapper<SaleStock> eq = Wrappers.<SaleStock>query().select("sum(IF(sale_type = 1, num, -num)) as num").eq("batch_no", batchNo).eq("type", "supplier");
        SaleStock one = saleStockService.getOne(eq);
        if (Objects.isNull(one)) {
            return 0;
        }
        return one.getNum();
    }

    /**
     * 采购数量
     *
     * @return
     */
    private Integer getPurchaseAmountBytime(Long startTime, Long endTime) {
        QueryWrapper<SaleStock> eq = Wrappers.<SaleStock>query().select("sum(num) as num").eq("type", "supplier").ge("sale_time", startTime).eq("sale_type", 1).le("sale_time", endTime);
        SaleStock one = saleStockService.getOne(eq);
        if (Objects.isNull(one)) {
            return 0;
        }
        return one.getNum();
    }


    /**
     * 库存数量
     *
     * @param batchNo
     * @return
     */
    private Integer getStockAmount(String batchNo) {
        QueryWrapper<GaiaWmsKucen> gaiaWmsKucenLambdaQueryWrapper = Wrappers.<GaiaWmsKucen>query();
        gaiaWmsKucenLambdaQueryWrapper.select("sum(wm_kcsl) as wm_kcsl").eq(StringUtils.isNotBlank(batchNo), "wm_pch", batchNo);
        GaiaWmsKucen one = gaiaWmsKucenService.getOne(gaiaWmsKucenLambdaQueryWrapper);

        if (Objects.isNull(one)) {
            return 0;
        }
        return one.getWmKcsl();
    }

    /**
     * 采购数量
     *
     * @param batchNo
     * @return
     */
    private Integer getStockAmount4Supplier(String batchNo) {
        QueryWrapper<GaiaWmsKucen> gaiaWmsKucenLambdaQueryWrapper = Wrappers.<GaiaWmsKucen>query();
        gaiaWmsKucenLambdaQueryWrapper.select("sum(wm_kcsl) as wm_kcsl").eq(StringUtils.isNotBlank(batchNo), "wm_pch", batchNo);
        GaiaWmsKucen one = gaiaWmsKucenService.getOne(gaiaWmsKucenLambdaQueryWrapper);

        if (Objects.isNull(one)) {
            return 0;
        }
        List<WholesaleSalesRecord> list = wholesaleSalesRecordService.list(Wrappers.<WholesaleSalesRecord>lambdaQuery().eq(StringUtils.isNotBlank(batchNo), WholesaleSalesRecord::getBatchNo, batchNo));
        if (CollectionUtils.isNotEmpty(list)) {
            Integer collect = list.stream().map(r -> {
                Integer usedNum = Objects.nonNull(r.getUsedNum()) ? r.getUsedNum() : 0;
                Integer totalNum = r.getTotalNum();
                return totalNum - usedNum;
            }).mapToInt(r -> r).sum();
            return one.getWmKcsl() + collect;
        }
        return 0;
    }


    /**
     * 销售
     *
     * @param batchNo
     * @return
     */
    private Integer getSaleAmount(String batchNo) {
        QueryWrapper<SaleStock> eq = Wrappers.<SaleStock>query().select("sum(IF(sale_type = 1, num, -num)) as num").eq("batch_no", batchNo).eq("test", 0).eq("type", "sale");
        SaleStock one = saleStockService.getOne(eq);
        if (Objects.isNull(one)) {
            return 0;
        }
        return one.getNum();
    }


    /**
     * 销售供应商数据
     *
     * @param batchNo
     * @return
     */
    private Integer getSaleAmount4Supplier(String batchNo) {
        QueryWrapper<SaleStock> eq = Wrappers.<SaleStock>query().select("sum(IF(sale_type = 1, num, -num)) as num").eq("batch_no", batchNo)
//                .eq("test", 0)
                .eq("type", "sale");
        SaleStock one = saleStockService.getOne(eq);
        if (Objects.isNull(one)) {
            return 0;
        }
        return one.getNum();
    }

    /**
     * 销售供应商数据
     *
     * @return
     */
    private Integer getSaleAmount4Supplier(Long startTime, Long endTime) {
        QueryWrapper<SaleStock> eq = Wrappers.<SaleStock>query().select("sum(IF(sale_type = 1, num, -num)) as num").ge("sale_time", startTime).le("sale_time", endTime).eq("type", "sale");
        SaleStock one = saleStockService.getOne(eq);
        if (Objects.isNull(one)) {
            return 0;
        }
        return one.getNum();
    }


    /**
     * 采购数量
     *
     * @param batchNo
     * @return
     */
    private Integer getPurchaseAmount4Supplier(String batchNo) {
        GaiaBatchInfo gaiaBatchInfo = gaiaBatchInfoService.getOne(Wrappers.<GaiaBatchInfo>lambdaQuery().eq(GaiaBatchInfo::getBatBatch, batchNo));
        if (Objects.isNull(gaiaBatchInfo)) {
            return 0;
        }
        return gaiaBatchInfo.getBatReceiveQty();
    }

    public static void main(String[] args) {

        System.out.println("0Y2024059121".substring(2, 6));
    }

    @GetResource(name = "配送单详情", path = "/stock/delivery/order", requiredLogin = true, requiredPermission = true)
    @ApiOperation("配送单详情")
    public ResponseData<DeliveryOrderDetailVO> deliveryOrderDetail(@RequestParam("billNo") String billNo1, @RequestParam("saleId") String saleId, @RequestParam(value = "templateType", required = false) String templateType) {
        SaleStock saleStock = saleStockService.getOne(Wrappers.<SaleStock>lambdaQuery().eq(SaleStock::getSaleId, saleId));
        String stoCode = saleStock.getStoCode();
        String billNo = saleStock.getBillNo();

        String time = RebateDateUtil.format(saleStock.getSaleTime());

        List<GaiaWmsDiaoboZ> list = gaiaWmsDiaoboZService.list(Wrappers.<GaiaWmsDiaoboZ>lambdaQuery().eq(GaiaWmsDiaoboZ::getWmPsdh, billNo)
                .eq(GaiaWmsDiaoboZ::getMatType, SaleStockTypeEnum.PD.getYaodeType())
                .eq(GaiaWmsDiaoboZ::getWmCjrq, time)
        );


        DeliveryOrderDetailVO deliveryOrderDetailVO = new DeliveryOrderDetailVO();
        TestBillDetail testBillDetail = testBillDetailService.getOne(Wrappers.<TestBillDetail>lambdaQuery().eq(TestBillDetail::getBillNo, saleId));
        if (Objects.isNull(testBillDetail)) {
            Long saleTime = saleStock.getSaleTime();
            testBillDetail = new TestBillDetail();
            String format = RebateDateUtil.format(saleTime);
            //20240604-001-04-0001
            int i1 = RandomUtil.randomInt(4);
            deliveryOrderDetailVO.setBoxNo(format + "-001-04-" + i1);
            testBillDetail.setBillNo(saleId);

        } else {
            deliveryOrderDetailVO = JSON.parseObject(testBillDetail.getInfo(), DeliveryOrderDetailVO.class);
        }
//        List<SaleStock> saleStocks = saleStockService.list(Wrappers.<SaleStock>lambdaQuery()
//                .eq(SaleStock::getBillNo, billNo)
////                .eq(SaleStock::getType, SaleStockTypeEnum.PD.getType())
////                .eq(SaleStock::getType, SaleStockTypeEnum.PD.getType())
//                .eq(SaleStock::getType, SaleStockTypeEnum.PD.getType())
//                .notIn(SaleStock::getStoCode, "100", "101", "114"));
        //空的是测试数据 随机生成
        List<SaleStock> saleStockList = Lists.newArrayList();
        if (CollectionUtils.isEmpty(list)) {

            List<String> saleIdList = deliveryOrderDetailVO.getSaleIdList();
            if (CollectionUtils.isEmpty(saleIdList)) {
                saleStockList = saleStockService.list(Wrappers.<SaleStock>lambdaQuery().eq(SaleStock::getStoCode, stoCode).eq(SaleStock::getType, SaleStockTypeEnum.PD.getType()).notIn(SaleStock::getSaleId, saleId).le(SaleStock::getSaleTime, saleStock.getSaleTime()).notIn(SaleStock::getStoCode, "100", "101", "114").last("limit " + RandomUtil.randomInt(10) + " ," + RandomUtil.randomInt(10)));
                saleStockList.add(saleStock);
            } else {
                List<String> saleIdList1 = deliveryOrderDetailVO.getSaleIdList();
                saleStockList = saleStockService.list(Wrappers.<SaleStock>lambdaQuery().in(SaleStock::getSaleId, saleIdList1));
            }

            List<String> collect = saleStockList.stream().map(r -> r.getSaleId()).collect(Collectors.toList());
            deliveryOrderDetailVO.setSaleIdList(collect);
            Long saleTime = saleStock.getSaleTime();
            deliveryOrderDetailVO.setBiller("陈芳琴");
            deliveryOrderDetailVO.setDeliveryOrderNo(billNo);
            deliveryOrderDetailVO.setPicker("潘艳萍");
            deliveryOrderDetailVO.setDeliveryDate(RebateDateUtil.format(saleTime));
            deliveryOrderDetailVO.setClient(stoCode);
            deliveryOrderDetailVO.setChecker("陈芳琴");
            testBillDetail.setInfo(JSON.toJSONString(deliveryOrderDetailVO));
        } else {
            saleStockList = saleStockService.list(Wrappers.<SaleStock>lambdaQuery().eq(SaleStock::getBillNo, billNo).eq(SaleStock::getType, SaleStockTypeEnum.PD.getType()).notIn(SaleStock::getStoCode, "100", "101", "114"));
            testBillDetail.setInfo(JSON.toJSONString(deliveryOrderDetailVO));
            GaiaWmsDiaoboZ gaiaWmsDiaoboZ = list.get(0);
            deliveryOrderDetailVO.setBiller(gaiaWmsDiaoboZ.getWmCjr());
            deliveryOrderDetailVO.setDeliveryOrderNo(billNo);
            deliveryOrderDetailVO.setDeliveryDate(gaiaWmsDiaoboZ.getWmCjrq());
            deliveryOrderDetailVO.setChecker(gaiaWmsDiaoboZ.getWmXgr());
            deliveryOrderDetailVO.setClientName(gaiaWmsDiaoboZ.getCustomer2Name());
            deliveryOrderDetailVO.setPicker("潘艳萍");
            String customer2 = gaiaWmsDiaoboZ.getCustomer2();
            deliveryOrderDetailVO.setClient(customer2);
        }
        testBillDetailService.saveOrUpdate(testBillDetail);

        List<SaleStockVO> saleStockVOS = fillInfo(saleStockList);
        List<GaiaStoreData> gaiaStoreData = gaiaStoreDataMapper.selectList(Wrappers.<GaiaStoreData>lambdaQuery().eq(GaiaStoreData::getStoCode, deliveryOrderDetailVO.getClient()));
        List<Store> stores = storeService.list(Wrappers.<Store>lambdaQuery().eq(Store::getStoreCode, deliveryOrderDetailVO.getClient()));
        if (CollectionUtils.isNotEmpty(gaiaStoreData)) {
            GaiaStoreData gaiaStoreData1 = gaiaStoreData.get(0);
            Store store = stores.get(0);
            deliveryOrderDetailVO.setClientAddress(gaiaStoreData1.getStoAdd());
            deliveryOrderDetailVO.setClientName(store.getStoreName());
        }
        Collections.shuffle(saleStockVOS);
        deliveryOrderDetailVO.setSaleStockVOList(saleStockVOS);
        return new SuccessResponseData<>(deliveryOrderDetailVO);
    }


    @GetResource(name = "销售单详情", path = "/stock/sale/order", requiredLogin = true, requiredPermission = true)
    @ApiOperation("销售单详情")
    public ResponseData<SaleOrderDetailVO> saleOrderDetail(@RequestParam("saleId") String saleId) {
        SaleStock saleStock = saleStockService.getOne(Wrappers.<SaleStock>lambdaQuery().eq(SaleStock::getSaleId, saleId));
        String gssdBillNo = saleStock.getBillNo();
        Integer test = saleStock.getTest();
        Long time = saleStock.getTime();
        Long time1 = saleStock.getTime();

        SaleOrderDetailVO saleOrderDetailVO = new SaleOrderDetailVO();
        TestBillDetail testBillDetail = testBillDetailService.getOne(Wrappers.<TestBillDetail>lambdaQuery().eq(TestBillDetail::getBillNo, saleId));
        if (Objects.equals(test, 0)) {
            List<GaiaSdSaleD> gaiaSdSaleDList = gaiaSdSaleDMapper.selectList(Wrappers.<GaiaSdSaleD>lambdaQuery().eq(GaiaSdSaleD::getGssdBillNo, gssdBillNo));
            List<GaiaSdSalePayMsg> gaiaSdSalePayMsgs = gaiaSdSalePayMsgMapper.selectList(Wrappers.<GaiaSdSalePayMsg>lambdaQuery().eq(GaiaSdSalePayMsg::getGsspmBillNo, gssdBillNo));
            GaiaSdSalePayMsg gaiaSdSalePayMsg = gaiaSdSalePayMsgs.get(0);
            GaiaSdSaleD gaiaSdSaleD = gaiaSdSaleDList.get(0);
            Store store = storeService.getOne(Wrappers.<Store>lambdaQuery().eq(Store::getStoreCode, gaiaSdSaleD.getGssdBrId()));
            String gssdDate = gaiaSdSaleD.getGssdDate();
            String gssdSalerId = gaiaSdSaleD.getGssdSalerId();

            if (Objects.isNull(testBillDetail)) {
                testBillDetail = new TestBillDetail();
                testBillDetail.setBillNo(saleId);
                if (Objects.isNull(time)) {
                    time = getRandomTime(store.getOpenDate(), store.getCloseDate(), gssdDate);
                }
                saleOrderDetailVO.setSaleTime(time);
            } else {
                saleOrderDetailVO = JSON.parseObject(testBillDetail.getInfo(), SaleOrderDetailVO.class);
                if (Objects.isNull(saleOrderDetailVO)) {
                    saleOrderDetailVO = new SaleOrderDetailVO();
                    if (Objects.isNull(time)) {
                        time = getRandomTime(store.getOpenDate(), store.getCloseDate(), gssdDate);
                    }
                    saleOrderDetailVO.setSaleTime(time);
                }
            }
            testBillDetail.setInfo(JSON.toJSONString(saleOrderDetailVO));
            testBillDetailService.saveOrUpdate(testBillDetail);

            saleOrderDetailVO.setStoreName(store.getStoreName());
            saleOrderDetailVO.setCashier(gaiaSdSalePayMsg.getGsspmId());
            saleOrderDetailVO.setSalesman(gssdSalerId);


            saleOrderDetailVO.setBillNo(gssdBillNo);

            List<String> proIdList = gaiaSdSaleDList.stream().map(GaiaSdSaleD::getGssdProId).collect(Collectors.toList());
            Map<String, GaiaProductBusiness> productBusinessMap = gaiaProductBusinessService.list(Wrappers.<GaiaProductBusiness>lambdaQuery().in(GaiaProductBusiness::getProSelfCode, proIdList)).stream().collect(Collectors.toMap(GaiaProductBusiness::getProSelfCode, Function.identity()));
            List<SaleOrderDetailVO.Payment> payments = gaiaSdSalePayMsgs.stream().map(r -> {
                SaleOrderDetailVO.Payment payment = new SaleOrderDetailVO.Payment();
                payment.setGsspmAmt(r.getGsspmAmt());
                payment.setGsspmName(r.getGsspmName());
                return payment;
            }).collect(Collectors.toList());
            List<SaleOrderDetailVO.SaleGoods> saleGoods = gaiaSdSaleDList.stream().map(r -> {
                SaleOrderDetailVO.SaleGoods saleGoods1 = new SaleOrderDetailVO.SaleGoods();
                saleGoods1.setGssdAmt(r.getGssdAmt());
                saleGoods1.setGssdPrc1(r.getGssdPrc1());
                saleGoods1.setGssdPrc2(r.getGssdPrc2());
                saleGoods1.setGssdProId(r.getGssdProId());
                saleGoods1.setGssdQty(r.getGssdQty());
                GaiaProductBusiness gaiaProductBusiness = productBusinessMap.get(r.getGssdProId());

                saleGoods1.setPlace(gaiaProductBusiness.getProPlace());
                saleGoods1.setProName(gaiaProductBusiness.getProName());
                saleGoods1.setSpec(gaiaProductBusiness.getProSpecs());
                saleGoods1.setBatch(r.getGssdBatchNo());
                saleGoods1.setBatExpireDate(gaiaProductBusiness.getProRegisterExdate());
                saleGoods1.setProductionEnterprise(gaiaProductBusiness.getProFactoryName());
                saleGoods1.setHolder(gaiaProductBusiness.getProHolder());
                return saleGoods1;
            }).collect(Collectors.toList());
            saleOrderDetailVO.setPaymentList(payments);
            saleOrderDetailVO.setSaleGoodsList(saleGoods);

            saleGoods.stream().map(SaleOrderDetailVO.SaleGoods::getGssdAmt).reduce(BigDecimal::add).ifPresent(saleOrderDetailVO::setRealTotalAmt);
            saleGoods.stream().map(r -> r.getGssdPrc1().multiply(new BigDecimal(r.getGssdQty()))).reduce(BigDecimal::add).ifPresent(saleOrderDetailVO::setTotalAmt);
            saleOrderDetailVO.setRealTotalAmt(saleOrderDetailVO.getRealTotalAmt().setScale(2, BigDecimal.ROUND_HALF_UP));
            saleOrderDetailVO.setTotalAmt(saleOrderDetailVO.getTotalAmt().setScale(2, BigDecimal.ROUND_HALF_UP));
            saleOrderDetailVO.setPreferentialTotalAmt(saleOrderDetailVO.getTotalAmt().subtract(saleOrderDetailVO.getRealTotalAmt()));
            if (Objects.nonNull(time1)) {
                saleOrderDetailVO.setSaleTime(time1);
            }
            return new SuccessResponseData<>(saleOrderDetailVO);
        } else {
            String stoCode = saleStock.getStoCode();
            String batchNo = saleStock.getBatchNo();
            if (Objects.isNull(testBillDetail)) {
                Store store = storeService.getOne(Wrappers.<Store>lambdaQuery().eq(Store::getStoreCode, stoCode));
                List<GaiaBatchInfo> gaiaBatchInfoList = gaiaBatchInfoService.list(Wrappers.<GaiaBatchInfo>lambdaQuery().eq(GaiaBatchInfo::getBatBatch, batchNo));
                testBillDetail = new TestBillDetail();
                testBillDetail.setBillNo(saleId);
                if (Objects.isNull(time)) {
                    time = getRandomTime(store.getOpenDate(), store.getCloseDate(), RebateDateUtil.format(saleStock.getSaleTime()));
                }
                saleOrderDetailVO.setSaleTime(time);
                saleOrderDetailVO.setStoreName(store.getStoreName());
                saleOrderDetailVO.setCashier("1102");
                saleOrderDetailVO.setSalesman("4000");
                String goodsId = saleStock.getGoodsId();
                Goods goods = goodsService.getById(goodsId);
                String commodityCode = goods.getCommodityCode();
                saleOrderDetailVO.setBillNo(gssdBillNo);
                Integer num = saleStock.getNum();
                GaiaProductBusiness productBusiness = gaiaProductBusinessService.getOne(Wrappers.<GaiaProductBusiness>lambdaQuery().eq(GaiaProductBusiness::getProSelfCode, commodityCode));
                BigDecimal proLsj = productBusiness.getProLsj();
                BigDecimal price = proLsj.multiply(new BigDecimal(num));

                SaleOrderDetailVO.Payment payment = new SaleOrderDetailVO.Payment();
                payment.setGsspmAmt(price);
                payment.setGsspmName("现金付");

                List<SaleOrderDetailVO.Payment> payments = com.google.common.collect.Lists.newArrayList(payment);

                SaleOrderDetailVO.SaleGoods saleGoods1 = new SaleOrderDetailVO.SaleGoods();
                saleGoods1.setGssdAmt(price);
                saleGoods1.setGssdPrc1(proLsj);
                saleGoods1.setGssdPrc2(price);
                saleGoods1.setGssdProId(commodityCode);
                saleGoods1.setGssdQty(num);

                saleGoods1.setPlace(productBusiness.getProPlace());
                saleGoods1.setProName(productBusiness.getProName());

                saleGoods1.setSpec(productBusiness.getProSpecs());
                saleGoods1.setBatch(gaiaBatchInfoList.get(0).getBatBatch());
                saleGoods1.setBatExpireDate(productBusiness.getProRegisterExdate());
                saleGoods1.setProductionEnterprise(productBusiness.getProFactoryName());
                saleGoods1.setHolder(productBusiness.getProHolder());
                List<SaleOrderDetailVO.SaleGoods> saleGoods = com.google.common.collect.Lists.newArrayList(saleGoods1);
                saleOrderDetailVO.setPaymentList(payments);
                saleOrderDetailVO.setSaleGoodsList(saleGoods);

                saleOrderDetailVO.setTotalAmt(saleGoods1.getGssdAmt());
                saleOrderDetailVO.setRealTotalAmt(saleGoods1.getGssdPrc2());
                saleOrderDetailVO.setRealTotalAmt(saleOrderDetailVO.getRealTotalAmt().setScale(2, BigDecimal.ROUND_HALF_UP));
                saleOrderDetailVO.setTotalAmt(saleOrderDetailVO.getTotalAmt().setScale(2, BigDecimal.ROUND_HALF_UP));
                saleOrderDetailVO.setPreferentialTotalAmt(saleGoods1.getGssdAmt().subtract(saleOrderDetailVO.getRealTotalAmt()));

                testBillDetail.setInfo(JSON.toJSONString(saleOrderDetailVO));

            } else {
                saleOrderDetailVO = JSON.parseObject(testBillDetail.getInfo(), SaleOrderDetailVO.class);
            }
            testBillDetailService.saveOrUpdate(testBillDetail);
            if (Objects.nonNull(time1)) {
                saleOrderDetailVO.setSaleTime(time1);
            }
            return new SuccessResponseData<>(saleOrderDetailVO);
        }

    }

    private Long getRandomTime(Date openDate, Date closeDate, String wmCjrq) {

        LocalTime localTimeOpen = LocalTime.of(openDate.getHours(), openDate.getMinutes());
        LocalTime localTimeClose = LocalTime.of(closeDate.getHours(), closeDate.getMinutes());
        //昨天
//        LocalDate date = LocalDate.now().minusDays(1);
        LocalDate date = LocalDate.parse(wmCjrq, SIMPLE_DATE_FORMAT1);

        LocalDateTime localDateTime = LocalDateTime.of(date, localTimeOpen);
        long epochSecondOpen = localDateTime.toEpochSecond(ZonedDateTime.now().getOffset());

        LocalDateTime localDateTimeClose = LocalDateTime.of(date, localTimeClose);
        long epochSecondClose = localDateTimeClose.toEpochSecond(ZonedDateTime.now().getOffset());

        return RandomUtil.randomLong(epochSecondOpen, epochSecondClose) * 1000;
    }

    @ResponseBody
    @PostResource(name = "进销存导出", path = "/vender/export", requiredLogin = false, requiredPermission = false)
    @ApiOperation("进销存导出")
    @BusinessLog
    public ResponseData<String> export(@RequestBody QueryStockRequest queryStockRequest, HttpServletResponse response) throws IOException {
        response.setHeader("Content-Disposition", "attachment;filename=" + "sale.xlsx");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        LoginUser loginUser = LoginContext.me().getLoginUser();
        Long userId = loginUser.getUserId();
//        Long userId = 1782228461448880130L;
        String goodsId = queryStockRequest.getGoodsId();
        String type = queryStockRequest.getType();
        if (Objects.equals(type, SaleStockTypeEnum.CD.getType())) {
            try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), BuyExportExcelVo.class).build()) {
                WriteSheet writeSheetYeah = EasyExcel.writerSheet("购进").build();
                int pageNo = 1;
                queryStockRequest.setPageSize(100);
                while (true) {
                    queryStockRequest.setPageNo(pageNo);
                    SuccessResponseData<PageResult<SaleStockVO>> pageResultSuccessResponseData = getPageResultSuccessResponseData(queryStockRequest, goodsId, userId, null);
                    List<SaleStockVO> rows = pageResultSuccessResponseData.getData().getRows();
                    if (CollectionUtils.isEmpty(rows)) {
                        break;
                    }
                    pageNo++;
                    List<BuyExportExcelVo> dataList = rows.stream().map(r -> {
                        BuyExportExcelVo buyExportExcelVo = new BuyExportExcelVo();
                        buyExportExcelVo.setBillDate(RebateDateUtil.format(r.getSaleTime()));
                        buyExportExcelVo.setProductName(r.getCommodityName());
                        buyExportExcelVo.setProductBatch(r.getBatch());
                        buyExportExcelVo.setProductBatchNo(r.getBatchNo());
                        buyExportExcelVo.setProductNum(Objects.equals(r.getSaleType(), 1) ? r.getNum() : -r.getNum());
                        buyExportExcelVo.setProductUnit(r.getCommodityUnit());
                        buyExportExcelVo.setProductSpec(r.getCommoditySpec());
                        buyExportExcelVo.setSupplierName(r.getSupplierName());
                        buyExportExcelVo.setProExpiryDate(r.getBatExpireDate());
                        buyExportExcelVo.setProductCode(r.getCommodityCode());
                        buyExportExcelVo.setIsTest(Objects.equals(r.getTest(), 1));
                        return buyExportExcelVo;
                    }).collect(Collectors.toList());
                    excelWriter.write(dataList, writeSheetYeah);
                }
            }
        } else if (Objects.equals(type, SaleStockTypeEnum.PD.getType())) {
            try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), StoreExportExcelVo.class).build()) {
                WriteSheet writeSheetYeah = EasyExcel.writerSheet("销售").build();
                int pageNo = 1;
                queryStockRequest.setPageSize(100);
                while (true) {
                    queryStockRequest.setPageNo(pageNo);
                    SuccessResponseData<PageResult<SaleStockVO>> pageResultSuccessResponseData = getPageResultSuccessResponseData(queryStockRequest, goodsId, userId, null);
                    List<SaleStockVO> rows = pageResultSuccessResponseData.getData().getRows();
                    if (CollectionUtils.isEmpty(rows)) {
                        break;
                    }
                    pageNo++;
                    List<StoreExportExcelVo> dataList = rows.stream().map(r -> {
                        StoreExportExcelVo buyExportExcelVo = new StoreExportExcelVo();
                        buyExportExcelVo.setBillDate(RebateDateUtil.format(r.getSaleTime()));
                        buyExportExcelVo.setProductName(r.getCommodityName());
                        buyExportExcelVo.setProductCode(r.getCommodityCode());
                        buyExportExcelVo.setProductBatch(r.getBatch());
                        buyExportExcelVo.setProductBatchNo(r.getBatchNo());
                        buyExportExcelVo.setProductNum(Objects.equals(r.getSaleType(), 2) ? r.getNum() : -r.getNum());
                        buyExportExcelVo.setProductUnit(r.getCommodityUnit());
                        buyExportExcelVo.setProductSpec(r.getCommoditySpec());
                        buyExportExcelVo.setStoreCode(r.getStoreCode());
                        buyExportExcelVo.setStoreName(r.getStoreName());
                        buyExportExcelVo.setProExpiryDate(r.getBatExpireDate());
                        buyExportExcelVo.setIsTest(Objects.equals(r.getTest(), 1));
                        buyExportExcelVo.setBillNo(r.getBillNo());
                        return buyExportExcelVo;
                    }).collect(Collectors.toList());
                    excelWriter.write(dataList, writeSheetYeah);
                }
            }
        } else if (Objects.equals(type, SaleStockTypeEnum.LS.getType())) {
            try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), SaleExportExcelVo.class).build()) {
                WriteSheet writeSheetYeah = EasyExcel.writerSheet("门店销售").build();
                int pageNo = 1;
                queryStockRequest.setPageSize(100);
                while (true) {
                    queryStockRequest.setPageNo(pageNo);
                    SuccessResponseData<PageResult<SaleStockVO>> pageResultSuccessResponseData = getPageResultSuccessResponseData(queryStockRequest, goodsId, userId, null);
                    List<SaleStockVO> rows = pageResultSuccessResponseData.getData().getRows();
                    if (CollectionUtils.isEmpty(rows)) {
                        break;
                    }
                    pageNo++;
                    List<SaleExportExcelVo> dataList = rows.stream().map(r -> {
                        SaleExportExcelVo buyExportExcelVo = new SaleExportExcelVo();
                        buyExportExcelVo.setBillDate(RebateDateUtil.formatTime(r.getSaleTime()));
                        buyExportExcelVo.setProductName(r.getCommodityName());
                        buyExportExcelVo.setProductBatch(r.getBatch());
                        buyExportExcelVo.setProductCode(r.getCommodityCode());
                        buyExportExcelVo.setSaleId(r.getSaleId());
                        if (StringUtils.isNotBlank(r.getGssdBillNo())) {
                            buyExportExcelVo.setBillNo(r.getGssdBillNo());
                        } else {
                            buyExportExcelVo.setBillNo(r.getBillNo());
                        }
                        buyExportExcelVo.setPayName(r.getPayName());
                        buyExportExcelVo.setProductBatchNo(r.getBatchNo());
                        buyExportExcelVo.setProductNum(Objects.equals(r.getSaleType(), 1) ? r.getNum() : -r.getNum());
                        buyExportExcelVo.setProductSpec(r.getCommoditySpec());
                        buyExportExcelVo.setStoreCode(r.getStoreCode());
                        buyExportExcelVo.setStoreName(r.getStoreName());
                        buyExportExcelVo.setPayName(r.getPayName());
                        buyExportExcelVo.setAmount(r.getReceivablePrice());
                        buyExportExcelVo.setProductUnit(r.getCommodityUnit());
                        return buyExportExcelVo;
                    }).collect(Collectors.toList());
                    excelWriter.write(dataList, writeSheetYeah);
                }
            }
        }
        return new SuccessResponseData<>();
    }

    @ResponseBody
    @PostResource(name = "库存导出", path = "/vender/stock/export", requiredLogin = false, requiredPermission = false)
    @ApiOperation("库存导出")
    @BusinessLog
    public ResponseData<String> stockExport(@RequestBody QueryWarehouseStockRequest queryStockRequest, HttpServletResponse response) throws IOException {
        response.setHeader("Content-Disposition", "attachment;filename=" + "stock.xlsx");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        LoginUser loginUser = LoginContext.me().getLoginUser();
        Long userId = loginUser.getUserId();
//        queryStockRequest.setTime("2024-09-30");

        try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), StockExportExcelVo.class).build()) {
            WriteSheet writeSheetYeah = EasyExcel.writerSheet("库存").build();
            int pageNo = 1;

            queryStockRequest.setPageSize(100);
            while (true) {
                queryStockRequest.setPageNo(pageNo);
                SuccessResponseData<PageResult<KucunVO>> stockData = getStockData(queryStockRequest, userId, "goods", null);
                PageResult<KucunVO> pageResult = stockData.getData();
                List<KucunVO> rows = pageResult.getRows();
                if (CollectionUtils.isEmpty(rows)) {
                    break;
                }
                pageNo++;
                List<StockExportExcelVo> collect = rows.stream().map(r -> {
                    StockExportExcelVo stockExportExcelVo = new StockExportExcelVo();
                    stockExportExcelVo.setStockDate(r.getStockTime());
                    stockExportExcelVo.setProductBatch(r.getWmPch());
                    stockExportExcelVo.setProductName(r.getGoodsName());
                    stockExportExcelVo.setProductSpec(r.getSpec());
                    stockExportExcelVo.setProductNum(r.getWmKcsl());
                    stockExportExcelVo.setProductUnit(r.getUnit());
                    stockExportExcelVo.setProductBatchNo(r.getBatch());
                    stockExportExcelVo.setBatCostPrice(r.getBatCostPrice());
                    stockExportExcelVo.setBatExpiredDate(r.getBatExpireDate());
                    stockExportExcelVo.setProductCode(r.getWmSpBm());
                    stockExportExcelVo.setManufacturer(r.getManufacturer());
                    stockExportExcelVo.setStoreCode(r.getProSite());
                    stockExportExcelVo.setStoreName(r.getStoName());
                    return stockExportExcelVo;
                }).collect(Collectors.toList());
                excelWriter.write(collect, writeSheetYeah);
            }
        }

        return new SuccessResponseData<>();
    }

    @ResponseBody
    @PostResource(name = "库存导出 后台", path = "/vender/back/stock/export", requiredLogin = false, requiredPermission = false)
    @ApiOperation("库存导出")
    @BusinessLog
    public ResponseData<String> stockExportBack(@RequestBody QueryWarehouseStockRequest queryStockRequest, HttpServletResponse response) throws IOException {
//        response.setHeader("Content-Disposition", "attachment;filename=" + "stock.xlsx");
//        response.setContentType("application/vnd.ms-excel");
//        response.setCharacterEncoding("utf-8");
//        LoginUser loginUser = LoginContext.me().getLoginUser();
//        Long userId = loginUser.getUserId();
        queryStockRequest.setTime("2024-08-31");
        File file = FileUtil.createNewFile("stock.xlsx");
        log.info(file.getAbsolutePath());

        try (ExcelWriter excelWriter = EasyExcel.write(new FileOutputStream(file), StockExportExcelVo.class).build()) {
            WriteSheet writeSheetYeah = EasyExcel.writerSheet("库存").build();
            int pageNo = 1;

            queryStockRequest.setPageSize(100);
            while (true) {
                queryStockRequest.setPageNo(pageNo);
                SuccessResponseData<PageResult<KucunVO>> stockData = getStockData(queryStockRequest, 1782228461448880130L, "goods", null);
                PageResult<KucunVO> pageResult = stockData.getData();
                List<KucunVO> rows = pageResult.getRows();
                if (CollectionUtils.isEmpty(rows)) {
                    break;
                }
                pageNo++;
                List<StockExportExcelVo> collect = rows.stream().map(r -> {
                    StockExportExcelVo stockExportExcelVo = new StockExportExcelVo();
                    stockExportExcelVo.setStockDate(r.getStockTime());
                    stockExportExcelVo.setProductBatch(r.getWmPch());
                    stockExportExcelVo.setProductName(r.getGoodsName());
                    stockExportExcelVo.setProductSpec(r.getSpec());
                    stockExportExcelVo.setProductNum(r.getWmKcsl());
                    stockExportExcelVo.setProductUnit(r.getUnit());
                    stockExportExcelVo.setProductBatchNo(r.getBatch());
                    stockExportExcelVo.setBatCostPrice(r.getBatCostPrice());
                    stockExportExcelVo.setBatExpiredDate(r.getBatExpireDate());
                    stockExportExcelVo.setProductCode(r.getWmSpBm());
                    stockExportExcelVo.setManufacturer(r.getManufacturer());
                    stockExportExcelVo.setStoreCode(r.getProSite());
                    stockExportExcelVo.setStoreName(r.getStoName());
                    return stockExportExcelVo;
                }).collect(Collectors.toList());
                excelWriter.write(collect, writeSheetYeah);
            }
        }

        return new SuccessResponseData<>();
    }


    @PostResource(name = "库存列表", path = "/vender/stock/list", requiredLogin = true, requiredPermission = true)
    @ApiOperation("库存列表")
    public ResponseData<PageResult<KucunVO>> stockVenderList(@RequestBody QueryWarehouseStockRequest queryStockRequest) {
        LoginUser loginUser = LoginContext.me().getLoginUser();
        Long userId = loginUser.getUserId();
        List<SimpleRoleInfo> simpleRoleInfoList = loginUser.getSimpleRoleInfoList();
        if (CollectionUtils.isEmpty(simpleRoleInfoList)) {
            return new SuccessResponseData<>(new PageResult());
        }
        SimpleRoleInfo venderRole = simpleRoleInfoList.stream().filter(r -> Objects.equals(r.getRoleCode(), "vender_role")).findAny().orElse(null);
        if (Objects.isNull(venderRole)) {
            return new SuccessResponseData<>(new PageResult());
        }
//        Long userId = 1767726677644812290L;
        return getStockData(queryStockRequest, userId, "goods", null);
    }

    @PostResource(name = "门店库存列表", path = "/store/stock/list", requiredLogin = true, requiredPermission = true)
    @ApiOperation("门店库存列表")
    public ResponseData<PageResult<KucunVO>> stockStoreList(@RequestBody QueryWarehouseStockRequest queryStockRequest) {
        LoginUser loginUser = LoginContext.me().getLoginUser();
        Long userId = loginUser.getUserId();
        List<SimpleRoleInfo> simpleRoleInfoList = loginUser.getSimpleRoleInfoList();
        if (CollectionUtils.isEmpty(simpleRoleInfoList)) {
            return new SuccessResponseData<>(new PageResult());
        }

//        Long userId = 1767726677644812290L;
        return getStockData(queryStockRequest, userId, "", "store");
    }

    /**
     * 查询库存列表
     *
     * @param queryStockRequest
     * @param userId
     * @return
     */
    private SuccessResponseData<PageResult<KucunVO>> getStockData(QueryWarehouseStockRequest queryStockRequest, Long userId, String goodsType, String supplierType) {
        List<UserRelation> userRelations = userRelationService.list(Wrappers.<UserRelation>lambdaQuery().in(UserRelation::getUserId, userId));
        if (CollectionUtils.isEmpty(userRelations)) {
            return new SuccessResponseData<>(new PageResult());
        }

        Map<String, List<UserRelation>> userRelationMap = userRelations.stream().collect(Collectors.groupingBy(UserRelation::getTargetType));
        List<UserRelation> goodRelations = userRelationMap.getOrDefault(AuthDataEnums.goods.getType(), Lists.newArrayList());
        List<UserRelation> supplierRelations = userRelationMap.getOrDefault(AuthDataEnums.supplier.getType(), Lists.newArrayList());
        List<UserRelation> storeCode = userRelationMap.getOrDefault(AuthDataEnums.store.getType(), Lists.newArrayList());
//        if (CollectionUtils.isEmpty(supplierRelations)) {
//            return new SuccessResponseData<>(new PageResult());
//        }


        List<String> goodsCodeList = null;
        if (CollectionUtils.isNotEmpty(goodRelations)) {
            List<String> goodsIdList = goodRelations.stream().map(UserRelation::getTargetId).collect(Collectors.toList());
            List<Goods> goods = goodsService.listByIds(goodsIdList);
            goodsCodeList = goods.stream().map(Goods::getCommodityCode).collect(Collectors.toList());
        }

        String batchNo = queryStockRequest.getBatchNo();

        IPage<SalesStockBatch> page = new Page<>(queryStockRequest.getPageNo(), queryStockRequest.getPageSize());

        LambdaQueryWrapper<SalesStockBatch> lambdaQueryWrapper = Wrappers.<SalesStockBatch>lambdaQuery()
//                        .in(CollectionUtils.isNotEmpty(supplierIdList), SalesStockBatch::getSupplierId, supplierIdList)
                .in(CollectionUtils.isNotEmpty(goodsCodeList), SalesStockBatch::getProCode, goodsCodeList)
                .in(StringUtils.isNotBlank(queryStockRequest.getTime()), SalesStockBatch::getTime, queryStockRequest.getTime())
                .eq(StringUtils.isNotBlank(queryStockRequest.getBatchNo()), SalesStockBatch::getBatchNo, queryStockRequest.getBatchNo()).and(r -> r.gt(SalesStockBatch::getNum, 0).or().gt(SalesStockBatch::getTestNum, 0));

        if (Objects.equals(supplierType, "store")) {
            List<String> storeCodeList = storeCode.stream().map(UserRelation::getTargetId).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(storeCodeList)) {
                return new SuccessResponseData<>(new PageResult());
            }
            lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(storeCodeList), SalesStockBatch::getStoCode, storeCodeList);
        }
        List<String> supplierIdList = supplierRelations.stream().map(UserRelation::getTargetId).collect(Collectors.toList());
        lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(supplierIdList), SalesStockBatch::getSupplierId, supplierIdList);


        if (Objects.equals(supplierType, "store")) {
            List<UserRelation> storeCodeList = userRelationMap.getOrDefault(AuthDataEnums.store.getType(), Lists.newArrayList());
            if (CollectionUtils.isNotEmpty(storeCodeList)) {
                List<String> collect1 = storeCodeList.stream().map(UserRelation::getTargetId).collect(Collectors.toList());
                lambdaQueryWrapper.in(SalesStockBatch::getStoCode, collect1);
            }
        }
        if (StringUtils.isNotEmpty(batchNo)) {
            List<GaiaBatchInfo> list = gaiaBatchInfoService.list(Wrappers.<GaiaBatchInfo>lambdaQuery().eq(GaiaBatchInfo::getBatBatchNo, batchNo));
            if (CollectionUtils.isEmpty(list)) {
                return new SuccessResponseData<>(new PageResult());
            }
            List<String> collect = list.stream().map(GaiaBatchInfo::getBatBatch).collect(Collectors.toList());
            lambdaQueryWrapper.in(SalesStockBatch::getBatchNo, collect);
        }

        if (StringUtils.isNotBlank(queryStockRequest.getGoodsId())) {
            Goods byId = goodsService.getById(queryStockRequest.getGoodsId());
            lambdaQueryWrapper.eq(SalesStockBatch::getProCode, byId.getCommodityCode());
        }

        if (CollectionUtils.isNotEmpty(queryStockRequest.getGoodsCodeList())) {
            List<Goods> goods = goodsService.listByIds(queryStockRequest.getGoodsCodeList());
            List<String> collect = goods.stream().map(Goods::getCommodityCode).collect(Collectors.toList());
            lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(collect), SalesStockBatch::getProCode, collect);
        }
        String stoCode = queryStockRequest.getStoCode();
        if (Objects.equals(stoCode, "100")) {
            lambdaQueryWrapper.eq(SalesStockBatch::getStoCode, "100");
        } else {
            lambdaQueryWrapper.eq(StringUtils.isNotBlank(stoCode), SalesStockBatch::getStoCode, stoCode);
            lambdaQueryWrapper.notIn(SalesStockBatch::getStoCode, Contants.CHAIN_LIST_RAL);
        }

        List<String> stoCodeList = queryStockRequest.getStoCodeList();
        lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(stoCodeList), SalesStockBatch::getStoCode, stoCodeList);


        page = salesStockBatchService.page(page, lambdaQueryWrapper);
        List<SalesStockBatch> records = page.getRecords();
        List<KucunVO> kucunVOS = fillInfoStock(records);

        return new SuccessResponseData<>(PageResultFactory.createPageResult(kucunVOS, page.getTotal(), (int) page.getSize(), (int) page.getCurrent()));
    }

    private List<KucunVO> fillInfoStock(List<SalesStockBatch> records) {
        if (CollectionUtils.isEmpty(records)) {
            return Lists.newArrayList();
        }
        List<String> procodeList = records.stream().map(SalesStockBatch::getProCode).collect(Collectors.toList());
        List<String> stocodeList = records.stream().map(SalesStockBatch::getStoCode).collect(Collectors.toList());
        List<String> batchList = records.stream().map(SalesStockBatch::getBatchNo).collect(Collectors.toList());
        Map<String, Goods> goodsMap = goodsService.list(Wrappers.<Goods>lambdaQuery().in(Goods::getCommodityCode, procodeList)).stream().collect(Collectors.toMap(Goods::getCommodityCode, Function.identity()));
        Map<String, Store> storeMap = storeService.list(Wrappers.<Store>lambdaQuery().in(Store::getStoreCode, stocodeList)).stream().collect(Collectors.toMap(Store::getStoreCode, Function.identity()));
        Map<String, GaiaBatchInfo> batchInfoMap = gaiaBatchInfoService.list(Wrappers.<GaiaBatchInfo>lambdaQuery().in(GaiaBatchInfo::getBatBatch, batchList)).stream().collect(Collectors.toMap(GaiaBatchInfo::getBatBatch, Function.identity()));

        List<String> proCodeList = goodsMap.values().stream().map(Goods::getCommodityCode).collect(Collectors.toList());
        Map<String, GaiaProductBusiness> gaiaProductBusinessMap = gaiaProductBusinessService.list(Wrappers.<GaiaProductBusiness>lambdaQuery().in(GaiaProductBusiness::getProSelfCode, proCodeList)).stream().collect(Collectors.toMap(GaiaProductBusiness::getProSelfCode, Function.identity()));

        List<KucunVO> collect = records.stream().map(r -> {
            KucunVO kucunVO = new KucunVO();
            Goods goods = goodsMap.get(r.getProCode());
            if (Objects.nonNull(goods)) {
                kucunVO.setSpec(goods.getCommoditySpec());
                kucunVO.setManufacturer(goods.getVender());
                kucunVO.setUnit(goods.getCommodityUnit());
                kucunVO.setGoodsName(goods.getCommodityName());
                kucunVO.setWmSpBm(goods.getCommodityCode());
                GaiaProductBusiness gaiaProductBusiness = gaiaProductBusinessMap.get(goods.getCommodityCode());
                if (Objects.nonNull(gaiaProductBusiness)) {
                    kucunVO.setProRegisterNo(gaiaProductBusiness.getProRegisterNo());
                    kucunVO.setProBasicCode(gaiaProductBusiness.getProBasicCode());
                    Double proHyj = gaiaProductBusiness.getProHyj();
                    if (Objects.nonNull(proHyj)) {
                        kucunVO.setProHyj(new BigDecimal(proHyj).setScale(4, BigDecimal.ROUND_HALF_UP));
                    } else {
                        kucunVO.setProHyj(new BigDecimal(0));
                    }
                }
            }
            Store store = storeMap.get(r.getStoCode());
            if (Objects.nonNull(store)) {
                kucunVO.setProSite(store.getStoreCode());
                kucunVO.setStoName(store.getStoreName());
            }
//            private String supplierCode;
//            private String supplierName;
            GaiaBatchInfo gaiaBatchInfo = batchInfoMap.get(r.getBatchNo());
            if (Objects.nonNull(gaiaBatchInfo)) {
                kucunVO.setBatExpireDate(gaiaBatchInfo.getBatExpiryDate());
                kucunVO.setWmPch(gaiaBatchInfo.getBatBatch());
                kucunVO.setBatch(gaiaBatchInfo.getBatBatchNo());
                kucunVO.setPrice(gaiaBatchInfo.getBatPoPrice());
                kucunVO.setBatCostPrice(gaiaBatchInfo.getBatPoPrice());
            }
            kucunVO.setStockTime(r.getTime());
            kucunVO.setWmKcsl(r.getNum() + r.getTestNum());
            return kucunVO;
        }).collect(Collectors.toList());
        return collect;
    }

//    KucunVO conver(SalesStockBatch salesStockBatch) {
//        if (salesStockBatch == null) {
//            return null;
//        }
//        KucunVO kucunVO = new KucunVO();
//        kucunVO.setSalesStockBatchId(salesStockBatch.getSalesStockBatchId());
//        kucunVO.setNum(salesStockBatch.getNum());
//        kucunVO.setTestNum(salesStockBatch.getTestNum());
//        kucunVO.setBatchNo(salesStockBatch.getBatchNo());
//        kucunVO.setTime(salesStockBatch.getTime());
//        kucunVO.setProCode(salesStockBatch.getProCode());
//        kucunVO.setStoCode(salesStockBatch.getStoCode());
//        kucunVO.setSupplierId(salesStockBatch.getSupplierId());
//        kucunVO.setDelFlag(salesStockBatch.getDelFlag());
//        kucunVO.setCreateTime(salesStockBatch.getCreateTime());
//        kucunVO.setCreateUser(salesStockBatch.getCreateUser());
//        kucunVO.setUpdateTime(salesStockBatch.getUpdateTime());
//        kucunVO.setUpdateUser(salesStockBatch.getUpdateUser());
//        return kucunVO;
//    }


    private void calStock(IPage<SaleStock> stockPage) {
        long total = stockPage.getTotal();
        if (total == 0) {
            return;
        }
        List<SaleStock> records = stockPage.getRecords();
        for (SaleStock record : records) {
            String type = record.getType();
            Integer num = record.getNum();
            String stoCode = record.getStoCode();
            String batchNo = record.getBatchNo();
            String goodsId = record.getGoodsId();


        }

    }


    private void calStock(List<GaiaWmsKucen> records) {
        for (GaiaWmsKucen record : records) {
            String wmPch = record.getWmPch();
            String wmSpBm = record.getWmSpBm();
            List<WholesaleSalesRecord> list = wholesaleSalesRecordService.list(Wrappers.<WholesaleSalesRecord>lambdaQuery().eq(WholesaleSalesRecord::getBatchNo, wmPch).eq(WholesaleSalesRecord::getProCode, wmSpBm));
            if (CollectionUtils.isNotEmpty(list)) {
                Integer collect = list.stream().map(r -> {
                    Integer usedNum = Objects.nonNull(r.getUsedNum()) ? r.getUsedNum() : 0;
                    Integer totalNum = r.getTotalNum();
                    return totalNum - usedNum;
                }).mapToInt(r -> r).sum();
                record.setWmKcsl(record.getWmKcsl() + collect);
            }
        }
    }

    @PostResource(name = "进销存列表", path = "/list", requiredLogin = true, requiredPermission = true)
    @ApiOperation("进销存列表")
    public ResponseData<PageResult<SaleStock>> list(@RequestBody QueryStockRequest queryStockRequest) {
        log.info("解析到一条数据:{}", JSON.toJSONString(queryStockRequest));

        Page page = new Page<>();
        page.setCurrent(queryStockRequest.getPageNo());
        page.setSize(queryStockRequest.getPageSize());
        String batchNo = queryStockRequest.getBatchNo();
        Integer canRebate = queryStockRequest.getCanRebate();
        Integer saleType = queryStockRequest.getSaleType();
        Long saleTimeBegin = queryStockRequest.getSaleTimeBegin();
        Long saleTimeEnd = queryStockRequest.getSaleTimeEnd();
        String goodsId = queryStockRequest.getGoodsId();
        String supplierId = queryStockRequest.getSupplierId();
        List<String> saleStockIdList = queryStockRequest.getSaleStockIdList();
        Integer test = queryStockRequest.getTest();
        String type = queryStockRequest.getType();

        LambdaQueryWrapper<SaleStock> lambdaQueryWrapper = Wrappers.<SaleStock>lambdaQuery().like(StringUtils.isNotBlank(goodsId), SaleStock::getGoodsId, goodsId).eq(StringUtils.isNotBlank(batchNo), SaleStock::getBatchNo, batchNo).eq(StringUtils.isNotBlank(type), SaleStock::getType, type).eq(Objects.nonNull(canRebate), SaleStock::getCanRebate, canRebate).eq(Objects.nonNull(saleType), SaleStock::getSaleType, saleType).eq(Objects.nonNull(test), SaleStock::getTest, test).eq(StringUtils.isNotBlank(supplierId), SaleStock::getSupplierId, supplierId).in(CollectionUtils.isNotEmpty(saleStockIdList), SaleStock::getSaleId, saleStockIdList).in(SaleStock::getStoCode, Contants.CHAIN_LIST).ge(Objects.nonNull(saleTimeBegin), SaleStock::getSaleTime, saleTimeBegin).le(Objects.nonNull(saleTimeEnd), SaleStock::getSaleTime, saleTimeEnd);
        Page<SaleStock> page1 = saleStockService.page(page, lambdaQueryWrapper);
        List<SaleStock> records = page1.getRecords();
        List saleStockVOS = fillInfo(records);
        page1.setRecords(saleStockVOS);
        return new SuccessResponseData<>(PageResultFactory.createPageResult(page1));
    }


    //    @PostResource(name = "打印信息", path = "/print/detail", requiredLogin = true, requiredPermission = true)
//    @ApiOperation("打印信息")
//    public ResponseData<PrintDetailVO> getPrintDetail(String saleId) {
//        SaleStock saleStock = saleStockService.getById(saleId);
//        String billNo = saleStock.getBillNo();
//        GaiaSdSalePayMsg gaiaSdSalePayMsg = gaiaSdSalePayMsgService.getOne(Wrappers.<GaiaSdSalePayMsg>lambdaQuery().eq(GaiaSdSalePayMsg::getGsspmBillNo, billNo));
//        Goods goods = goodsService.getById(saleStock.getGoodsId());
//        GaiaProductBusiness gaiaProductBusiness = gaiaProductBusinessService.getOne(Wrappers.<GaiaProductBusiness>lambdaQuery().eq(GaiaProductBusiness::getProCode, goods.getCommodityCode()));
//
//
//        PrintDetailVO printDetailVO = new PrintDetailVO();
//        printDetailVO.setAssistant();
//        printDetailVO.setCashier();
//        printDetailVO.setNum();
//        printDetailVO.setHolder(gaiaProductBusiness.get);
//        printDetailVO.setBatchNo();
//        printDetailVO.setCommodityCode(gaiaProductBusiness.getProCode());
//        printDetailVO.setCommodityName(gaiaProductBusiness.getProName());
//        printDetailVO.setCommoditySpec(gaiaProductBusiness.getProSpecs());
//        printDetailVO.setPayType();
//        printDetailVO.setOddNumber();
//        printDetailVO.setOriginalPrice();
//        printDetailVO.setSaleTime();
//        printDetailVO.setProductionEnterprise();
//        printDetailVO.setTotalDiscounts();
//        printDetailVO.setReceivedPrice();
//        printDetailVO.setStoreName();
//        printDetailVO.setReceivablePrice();
//
//
//
//        return new SuccessResponseData<>(PageResultFactory.createPageResult(page1));
//    }
    private List<KucunVO> fillInfoGaiaWmsKucen(List<GaiaWmsKucen> records) {
        if (CollectionUtils.isNotEmpty(records)) {
            List<String> goodsCodeList = records.stream().map(GaiaWmsKucen::getWmSpBm).collect(Collectors.toList());
            Map<String, Goods> goodsMap = goodsService.list(Wrappers.<Goods>lambdaQuery().in(Goods::getCommodityCode, goodsCodeList)).stream().collect(Collectors.toMap(Goods::getCommodityCode, Function.identity()));
            Map<String, GaiaBatchInfo> collect = gaiaBatchInfoService.list(Wrappers.<GaiaBatchInfo>lambdaQuery().in(GaiaBatchInfo::getBatBatch, records.stream().map(GaiaWmsKucen::getWmPch).collect(Collectors.toList()))).stream().collect(Collectors.toMap(GaiaBatchInfo::getBatBatch, Function.identity()));
            return records.stream().map(r -> convert(r, goodsMap.get(r.getWmSpBm()))).collect(Collectors.toList());
        }
        return Lists.newArrayList();
    }

    private KucunVO convert(GaiaWmsKucen r, Goods goods) {


        return null;
    }


    private List<SaleStockVO> fillInfo(List<SaleStock> records) {
        if (CollectionUtils.isNotEmpty(records)) {
            List<String> supplierIdList = records.stream().map(SaleStock::getSupplierId).collect(Collectors.toList());
            List<String> goodsIdList = records.stream().map(SaleStock::getGoodsId).collect(Collectors.toList());
            List<String> storeCodeList = records.stream().map(SaleStock::getStoCode).collect(Collectors.toList());
            List<String> batchNoList = records.stream().map(SaleStock::getBatchNo).collect(Collectors.toList());
            List<String> gssdBillNoList = records.stream().map(SaleStock::getBillNo).filter(StringUtils::isNotEmpty).collect(Collectors.toList());
            gssdBillNoList.addAll(records.stream().map(SaleStock::getGssdBillNo).filter(StringUtils::isNotEmpty).collect(Collectors.toList()));
            Map<String, List<GaiaSdSalePayMsg>> gaiaSdSalePayMsgList = gaiaSdSalePayMsgMapper.selectList(Wrappers.<GaiaSdSalePayMsg>lambdaQuery()
                            .in(GaiaSdSalePayMsg::getGsspmBillNo, gssdBillNoList))
                    .stream().collect(Collectors.groupingBy(GaiaSdSalePayMsg::getGsspmBillNo));

            Map<String, Supplier> supplierMap = supplierService.listByIds(supplierIdList).stream().collect(Collectors.toMap(Supplier::getSupplierId, Function.identity()));
            Map<String, Goods> goodsMap = goodsService.listByIds(goodsIdList).stream().collect(Collectors.toMap(Goods::getGoodsId, Function.identity()));
            Map<String, Store> storeMap = storeService.list(Wrappers.<Store>lambdaQuery().in(Store::getStoreCode, storeCodeList)).stream().collect(Collectors.toMap(Store::getStoreCode, Function.identity()));
            Map<String, GaiaBatchInfo> batchInfoMap = gaiaBatchInfoService.list(Wrappers.<GaiaBatchInfo>lambdaQuery().in(GaiaBatchInfo::getBatBatch, batchNoList)).stream().collect(Collectors.toMap(GaiaBatchInfo::getBatBatch, Function.identity()));
            Map<String, GaiaSdSaleH> gaiaSdSaleHMap = gaiaSdSaleHMapper.selectList(Wrappers.<GaiaSdSaleH>lambdaQuery().in(GaiaSdSaleH::getGsshBillNo, gssdBillNoList)).stream().collect(Collectors.toMap(GaiaSdSaleH::getGsshBillNo, Function.identity()));
            List<String> proCodeList = goodsMap.values().stream().map(Goods::getCommodityCode).collect(Collectors.toList());
            Map<String, GaiaProductBusiness> gaiaProductBusinessMap = gaiaProductBusinessService.list(Wrappers.<GaiaProductBusiness>lambdaQuery().in(GaiaProductBusiness::getProSelfCode, proCodeList)).stream().collect(Collectors.toMap(GaiaProductBusiness::getProSelfCode, Function.identity()));

            List<SaleStockVO> collect = records.stream().map(r -> {
                GaiaBatchInfo gaiaBatchInfo = batchInfoMap.get(r.getBatchNo());
                Goods goods = goodsMap.get(r.getGoodsId());
                SaleStockVO conver = saleStockConverter.conver(r, goods, supplierMap.get(r.getSupplierId()), gaiaBatchInfo);
                GaiaSdSaleH gaiaSdSaleH = gaiaSdSaleHMap.get(r.getGssdBillNo());
                if (Objects.nonNull(gaiaSdSaleH)) {
                    String gsshDate = gaiaSdSaleH.getGsshDate();
                    String gsshTime = gaiaSdSaleH.getGsshTime();
                    LocalDateTime parse = LocalDateTime.parse(gsshDate + gsshTime, SIMPLE_DATE_FORMAT2);
                    conver.setSaleTime(parse.toInstant(ZonedDateTime.now().getOffset()).toEpochMilli());
                } else {
                    GaiaSdSaleH gaiaSdSaleH2 = gaiaSdSaleHMap.get(r.getBillNo());
                    if (Objects.nonNull(gaiaSdSaleH2)) {
                        String gsshDate = gaiaSdSaleH2.getGsshDate();
                        String gsshTime = gaiaSdSaleH2.getGsshTime();
                        LocalDateTime parse = LocalDateTime.parse(gsshDate + gsshTime, SIMPLE_DATE_FORMAT2);
                        conver.setSaleTime(parse.toInstant(ZonedDateTime.now().getOffset()).toEpochMilli());
                    } else {
                        conver.setTime(Objects.isNull(r.getTime()) ? r.getSaleTime() : r.getTime());
                    }
                }
                String batch = conver.getBatch();
                if (StringUtils.isEmpty(batch) && Objects.nonNull(gaiaBatchInfo)) {
                    conver.setBatch(gaiaBatchInfo.getBatBatchNo());
                    conver.setBatProductDate(gaiaBatchInfo.getBatProductDate());
                }
                if (Objects.nonNull(goods)) {
                    GaiaProductBusiness gaiaProductBusiness = gaiaProductBusinessMap.get(goods.getCommodityCode());
                    if (Objects.nonNull(gaiaProductBusiness)) {
                        conver.setProRegisterNo(gaiaProductBusiness.getProRegisterNo());
                        conver.setProBasicCode(gaiaProductBusiness.getProBasicCode());
                        conver.setHolder(gaiaProductBusiness.getProHolder());
                        conver.setVender(gaiaProductBusiness.getProFactoryName());
                        conver.setProForm(gaiaProductBusiness.getProForm());

                        Float proCgj = gaiaProductBusiness.getProCgj();
                        if (Objects.nonNull(proCgj)) {
                            conver.setProHyj(new BigDecimal(proCgj).setScale(4, BigDecimal.ROUND_HALF_UP));
                            conver.setPrice(new BigDecimal(proCgj).setScale(4, BigDecimal.ROUND_HALF_UP));
                        } else {
                            conver.setProHyj(new BigDecimal(0));
                            conver.setPrice(new BigDecimal(0));
                        }
                    }
                    BigDecimal price = r.getPrice();
                    price = Objects.isNull(price) ? new BigDecimal(0) : price;
                    conver.setReceivablePrice(price.multiply(new BigDecimal(r.getNum())));
                }
                Store store = storeMap.get(r.getStoCode());
                if (Objects.nonNull(store)) {
                    conver.setStoreName(store.getStoreName());
                }
//                if (Objects.nonNull(gaiaBatchInfo)) {
//                    conver.setPrice(gaiaBatchInfo.getBatPoPrice());
//                }
                conver.setBillNo(r.getBillNo());
//                conver.setNum(r.getNum() + r.());
                Integer auditStatus = r.getAuditStatus();
                conver.setAuditStatus(Objects.isNull(auditStatus) ? 0 : auditStatus);
                conver.setTest(Objects.isNull(r.getTest()) ? 0 : r.getTest());
                conver.setGssdBillNo(r.getGssdBillNo());
                BigDecimal distributionPrice = r.getDistributionPrice();
                Integer num = r.getNum();
                if (Objects.nonNull(distributionPrice) && Objects.nonNull(num)) {
                    conver.setDistributionTotalPrice(distributionPrice.multiply(new BigDecimal(num)).setScale(4, BigDecimal.ROUND_HALF_UP));
                    conver.setDistributionPrice(distributionPrice.setScale(4, BigDecimal.ROUND_HALF_UP));
                } else {
                    conver.setDistributionPrice(conver.getPrice());
                    conver.setDistributionTotalPrice(conver.getReceivablePrice());
                }
                String payName = gaiaSdSalePayMsgList.getOrDefault(r.getBillNo(), Lists.newArrayList()).stream()
                        .map(GaiaSdSalePayMsg::getGsspmName).collect(Collectors.joining(","));

                List<GaiaSdSalePayMsg> gaiaSdSalePayMsgs = gaiaSdSalePayMsgList.get(r.getBillNo());

                if (CollectionUtils.isEmpty(gaiaSdSalePayMsgs)) {
                    Double receivablePrice = r.getReceivablePrice();
                    if (Objects.nonNull(receivablePrice)) {
                        conver.setReceivablePrice(BigDecimal.valueOf(receivablePrice));
                    }
                } else {
                    BigDecimal total = gaiaSdSalePayMsgs.stream().map(GaiaSdSalePayMsg::getGsspmAmt).reduce(BigDecimal.ZERO, BigDecimal::add);
                    conver.setReceivablePrice(total);
                }

                if (StringUtils.isNotEmpty(payName)) {
                    conver.setPayName(payName);
                } else {
                    conver.setPayName("现金");
                }
                if (Objects.equals(conver.getType(), SaleStockTypeEnum.LS.getType())) {
                    if (StringUtils.isNotBlank(r.getGssdBillNo())) {
                        conver.setBillNo(r.getGssdBillNo());
                    } else {
                        conver.setBillNo(r.getBillNo());
                    }
                }


//                //审计下
//                String batExpireDate = conver.getBatExpireDate();
//                if (StringUtils.isEmpty(batExpireDate)) {
//
//                }
                return conver;
            }).collect(Collectors.toList());
            return collect;
        }
        return Lists.newArrayList();
    }


    @PostResource(name = "厂家进销存列表", path = "/vender/list", requiredLogin = true, requiredPermission = true)
    @ApiOperation("厂家进销存列表")
    public ResponseData<PageResult<SaleStockVO>> listVender(@RequestBody QueryStockRequest queryStockRequest) {
        log.info("解析到一条数据:{}", JSON.toJSONString(queryStockRequest));

//        Page page = new Page<>();
//        page.setCurrent(queryStockRequest.getPageNo());
//        page.setSize(queryStockRequest.getPageSize());
//        String batchNo = queryStockRequest.getBatchNo();
//        Integer canRebate = queryStockRequest.getCanRebate();
//        Integer saleType = queryStockRequest.getSaleType();
//        Long saleTimeBegin = queryStockRequest.getSaleTimeBegin();
//        Long saleTimeEnd = queryStockRequest.getSaleTimeEnd();
//        String goodsId = queryStockRequest.getGoodsId();
//        String supplierId = queryStockRequest.getSupplierId();
//        String type = queryStockRequest.getType();
//        String storeCode = queryStockRequest.getStoreCode();

        LoginUser loginUser = LoginContext.me().getLoginUser();
        Long userId = loginUser.getUserId();
        List<SimpleRoleInfo> simpleRoleInfoList = loginUser.getSimpleRoleInfoList();
        if (CollectionUtils.isEmpty(simpleRoleInfoList)) {
            return new SuccessResponseData<>(new PageResult());
        }
//        SimpleRoleInfo venderRole = simpleRoleInfoList.stream().filter(r -> Objects.equals(r.getRoleCode(), "vender_role")).findAny().orElse(null);
//        if (Objects.isNull(venderRole)) {
//            return new SuccessResponseData<>(new PageResult());
//        }
//        Long userId = 1844945257217712129L;
        String goodsId = queryStockRequest.getGoodsId();
        return getPageResultSuccessResponseData(queryStockRequest, goodsId, userId, null);
    }

    @PostResource(name = "厂家进销存统计", path = "/vender/statistics", requiredLogin = true, requiredPermission = true)
    @ApiOperation("厂家进销存统计")
    public ResponseData<SaleStock> listVenderStatistics(@RequestBody QueryStockRequest queryStockRequest) {
        log.info("解析到一条数据:{}", JSON.toJSONString(queryStockRequest));


//        Page page = new Page<>();
//        page.setCurrent(queryStockRequest.getPageNo());
//        page.setSize(queryStockRequest.getPageSize());
//        String batchNo = queryStockRequest.getBatchNo();
//        Integer canRebate = queryStockRequest.getCanRebate();
//        Integer saleType = queryStockRequest.getSaleType();
//        Long saleTimeBegin = queryStockRequest.getSaleTimeBegin();
//        Long saleTimeEnd = queryStockRequest.getSaleTimeEnd();
//        String goodsId = queryStockRequest.getGoodsId();
//        String supplierId = queryStockRequest.getSupplierId();
//        String type = queryStockRequest.getType();
//        String storeCode = queryStockRequest.getStoreCode();

        SaleStock statistics = statistics(queryStockRequest, queryStockRequest.getGoodsId(), LoginContext.me().getLoginUser().getUserId());
        return new SuccessResponseData<>(statistics);
    }


    @PostResource(name = "门店进销存列表", path = "/store/list", requiredLogin = true, requiredPermission = true)
    @ApiOperation("门店进销存列表")
    public ResponseData<PageResult<SaleStockVO>> listStore(@RequestBody QueryStockRequest queryStockRequest) {
        log.info("解析到一条数据:{}", JSON.toJSONString(queryStockRequest));

//        Page page = new Page<>()
//        page.setCurrent(queryStockRequest.getPageNo());
//        page.setSize(queryStockRequest.getPageSize());
//        String batchNo = queryStockRequest.getBatchNo();
//        Integer canRebate = queryStockRequest.getCanRebate();
//        Integer saleType = queryStockRequest.getSaleType();
//        Long saleTimeBegin = queryStockRequest.getSaleTimeBegin();
//        Long saleTimeEnd = queryStockRequest.getSaleTimeEnd();
//        String goodsId = queryStockRequest.getGoodsId();
//        String supplierId = queryStockRequest.getSupplierId();
//        String type = queryStockRequest.getType();
//        String storeCode = queryStockRequest.getStoreCode();


        LoginUser loginUser = LoginContext.me().getLoginUser();
        Long userId = loginUser.getUserId();
        List<SimpleRoleInfo> simpleRoleInfoList = loginUser.getSimpleRoleInfoList();
        if (CollectionUtils.isEmpty(simpleRoleInfoList)) {
            return new SuccessResponseData<>(new PageResult());
        }

        String goodsId = queryStockRequest.getGoodsId();

        return getPageResultSuccessResponseData(queryStockRequest, goodsId, userId, "store");
    }

//    @PostResource(name = "门店进销存列表统计", path = "/store/statistics", requiredLogin = true, requiredPermission = true)
//    @ApiOperation("门店进销存列表统计")
//    public ResponseData<SaleStock> listStoreStatistics(@RequestBody QueryStockRequest queryStockRequest) {
//        log.info("解析到一条数据:{}", JSON.toJSONString(queryStockRequest));
//        SaleStock statistics = statistics(queryStockRequest, queryStockRequest.getGoodsId(), LoginContext.me().getLoginUser().getUserId());
//        return new SuccessResponseData<>(statistics);
//    }


    /**
     * 查询进销存列表
     *
     * @param queryStockRequest
     * @param goodsId
     * @param userId
     * @param queryType         null查供应商 store查门店的
     * @return
     */
    private SuccessResponseData<PageResult<SaleStockVO>> getPageResultSuccessResponseData(QueryStockRequest queryStockRequest, String goodsId, Long userId, String queryType) {
        LambdaQueryWrapper<SaleStock> saleStockLambdaQueryWrapper = Wrappers.<SaleStock>lambdaQuery();

        LambdaQueryWrapper<SaleStock> lambdaQueryWrapper = buildSaleStockWrapper(saleStockLambdaQueryWrapper, queryStockRequest, goodsId, userId);
        if (Objects.isNull(lambdaQueryWrapper)) {
            return new SuccessResponseData<>(new PageResult());
        }

        if (Objects.equals(queryType, "store")) {
            List<UserRelation> userRelations = userRelationService.list(Wrappers.<UserRelation>lambdaQuery().in(UserRelation::getUserId, userId));
            Map<String, List<UserRelation>> userRelationMap = userRelations.stream().collect(Collectors.groupingBy(UserRelation::getTargetType));
            List<UserRelation> storeCodeList = userRelationMap.getOrDefault(AuthDataEnums.store.getType(), Lists.newArrayList());
            if (CollectionUtils.isNotEmpty(storeCodeList)) {
                List<String> collect1 = storeCodeList.stream().map(UserRelation::getTargetId).collect(Collectors.toList());
                lambdaQueryWrapper.in(SaleStock::getStoCode, collect1);
            }
        }
        IPage<SaleStock> page = new <SaleStock>Page(queryStockRequest.getPageNo(), queryStockRequest.getPageSize());
        page = saleStockService.page(page, lambdaQueryWrapper);
        List<SaleStock> records = page.getRecords();
        Page<SaleStockVO> page2 = new Page(page.getCurrent(), page.getSize());
        page2.setTotal(page.getTotal());
        List<SaleStockVO> saleStockVOS = fillInfo(records);
        page2.setRecords(saleStockVOS);
        return new SuccessResponseData<>(PageResultFactory.createPageResult(page2));
    }

    /**
     * 进销存统计
     *
     * @param queryStockRequest
     * @param goodsId
     * @param userId
     * @return
     */
    private SaleStock statistics(QueryStockRequest queryStockRequest, String goodsId, Long userId) {
        QueryWrapper<SaleStock> query = Wrappers.query();
        QueryWrapper<SaleStock> select = Wrappers.<SaleStock>query().select("sum(num)");
        LambdaQueryWrapper<SaleStock> lambda = select.lambda();
        lambda = buildSaleStockWrapper(lambda, queryStockRequest, goodsId, userId);
        SaleStock one = saleStockService.getOne(lambda);
        return one;
    }

    private LambdaQueryWrapper<SaleStock> buildSaleStockWrapper(LambdaQueryWrapper<SaleStock> lambdaQueryWrapper, QueryStockRequest queryStockRequest, String goodsId, Long userId) {
        SysUser userInfoByUserId = sysUserService.getById(userId);
        UserExtend userExtend = userExtendService.getOne(Wrappers.<UserExtend>lambdaQuery().eq(UserExtend::getUserId, userId));
        //超管
        if (!Objects.equals("Y", userInfoByUserId.getSuperAdminFlag())) {
            List<UserRelation> userRelations = userRelationService.list(Wrappers.<UserRelation>lambdaQuery().in(UserRelation::getUserId, userId));
            if (CollectionUtils.isEmpty(userRelations)) {
                return null;
            }
            Map<String, List<UserRelation>> userRelationMap = userRelations.stream().collect(Collectors.groupingBy(UserRelation::getTargetType));
            List<UserRelation> goodRelations = userRelationMap.getOrDefault(AuthDataEnums.goods.getType(), Lists.newArrayList());
            List<UserRelation> supplierRelations = userRelationMap.getOrDefault(AuthDataEnums.supplier.getType(), Lists.newArrayList());
            //销售数据给全部 不区分渠道外
            if (CollectionUtils.isNotEmpty(supplierRelations)) {
                List<String> collect = supplierRelations.stream().map(UserRelation::getTargetId).collect(Collectors.toList());
                lambdaQueryWrapper.in(SaleStock::getSupplierId, collect);
//            lambdaQueryWrapper.and(r -> r.ge(SaleStock::getSaleTime, 1714492800000L)
//                    .in(SaleStock::getSupplierId, collect)
//                    .or(z -> z.le(SaleStock::getSaleTime, 1718294400000L)));
            }
            if (CollectionUtils.isNotEmpty(goodRelations)) {
                List<String> collect1 = goodRelations.stream().map(UserRelation::getTargetId).collect(Collectors.toList());
                lambdaQueryWrapper.in(SaleStock::getGoodsId, collect1);
            }
        }


        String type = queryStockRequest.getType();
        String batchNo = queryStockRequest.getBatchNo();
        lambdaQueryWrapper.eq(Objects.nonNull(queryStockRequest.getSaleType()), SaleStock::getSaleType, queryStockRequest.getSaleType()).eq(Objects.nonNull(goodsId), SaleStock::getGoodsId, goodsId).ge(Objects.nonNull(queryStockRequest.getSaleTimeBegin()), SaleStock::getSaleTime, queryStockRequest.getSaleTimeBegin())
                .le(Objects.nonNull(queryStockRequest.getSaleTimeEnd()), SaleStock::getSaleTime, queryStockRequest.getSaleTimeEnd());

        if (StringUtils.isNotBlank(queryStockRequest.getGoodsId())) {
            lambdaQueryWrapper.eq(SaleStock::getGoodsId, queryStockRequest.getGoodsId());
        }


        if (StringUtils.isNotEmpty(batchNo)) {
            List<GaiaBatchInfo> list = gaiaBatchInfoService.list(Wrappers.<GaiaBatchInfo>lambdaQuery().eq(GaiaBatchInfo::getBatBatchNo, batchNo));
            if (CollectionUtils.isEmpty(list)) {
                return null;
            }
            List<String> collect = list.stream().map(GaiaBatchInfo::getBatBatch).collect(Collectors.toList());
            lambdaQueryWrapper.in(SaleStock::getBatchNo, collect);
        }
        List<SaleStockImportTime> saleStockImportTimes = saleStockImportTimeService.list(Wrappers.<SaleStockImportTime>lambdaQuery()
                .eq(SaleStockImportTime::getUserId, userId)
                .eq(SaleStockImportTime::getType, type)
        );
        if (Objects.equals(userId, 1782228461448880130L) || CollectionUtils.isNotEmpty(saleStockImportTimes)) {
            lambdaQueryWrapper.and(and -> {
                //阿斯利康 只给5月1号之后的
                if ((Objects.equals(type, SaleStockTypeEnum.CD.getType()))) {
                    if (!Objects.equals("Y", userInfoByUserId.getSuperAdminFlag()) && Objects.equals(userId, 1782228461448880130L)) {
                        //todo 5.1之后给真实数据 5.1之前给tag =w0crdxdq50ss的数据
                        and.and(r ->
                                r.ge(CollectionUtils.isEmpty(saleStockImportTimes), SaleStock::getSaleTime, 1714492800000L)
                                        .and(CollectionUtils.isEmpty(saleStockImportTimes), z -> z.eq(SaleStock::getTag, "").or(o -> o.isNull(SaleStock::getTag)))
//                                .eq(SaleStock::getTest, 0)
                                        .or(z -> z.eq(SaleStock::getTag, "w0crdxdq50ss")
                                                .le(SaleStock::getSaleTime, 1714492800000L)));
                    }
                } else if (Objects.equals(type, SaleStockTypeEnum.PD.getType())) {
                    if (!Objects.equals("Y", userInfoByUserId.getSuperAdminFlag()) && Objects.equals(userId, 1782228461448880130L)) {
//
                        and.and(r ->
                                r
                                        .eq(CollectionUtils.isEmpty(saleStockImportTimes), SaleStock::getTest, 0)
                                        .and(CollectionUtils.isEmpty(saleStockImportTimes), z -> z.eq(SaleStock::getTag, "").or(o -> o.isNull(SaleStock::getTag)))
                                        .ge(CollectionUtils.isEmpty(saleStockImportTimes), SaleStock::getSaleTime, 1718294400000L)
                                        .or(z -> z.eq(SaleStock::getTest, 0)
                                                .le(SaleStock::getSaleTime, 1718294400000L)
                                                .ge(SaleStock::getSaleTime, 1717171200000L)
                                        )
                                        .or(z -> z.eq(SaleStock::getTag, "w0crdxdq50ss")
                                                .le(SaleStock::getSaleTime, 1718294400000L))

                        );

                    }
                } else if (Objects.equals(type, SaleStockTypeEnum.LS.getType())) {
                    if (!Objects.equals("Y", userInfoByUserId.getSuperAdminFlag()) && Objects.equals(userId, 1782228461448880130L)) {
                        //todo 5.1之后给真实数据 5.1之前给tag =w0crdxdq50ss的数据
                        and.and(r -> r
                                .eq(CollectionUtils.isEmpty(saleStockImportTimes), SaleStock::getTest, 0)
                                .and(CollectionUtils.isEmpty(saleStockImportTimes), z -> z.eq(SaleStock::getTag, "").or(o -> o.isNull(SaleStock::getTag)))
                                .ge(CollectionUtils.isEmpty(saleStockImportTimes), SaleStock::getSaleTime, 1717171200000L)
                                .or(z -> z.eq(SaleStock::getTag, "w0crdxdq50ss")
                                        .le(SaleStock::getSaleTime, 1717171200000L)
                                ));
                    }
                }

                if (!Objects.equals("Y", userInfoByUserId.getSuperAdminFlag())) {
                    if (CollectionUtils.isNotEmpty(saleStockImportTimes)) {
                        and.or(or -> {
                            or.and(z -> {
                                for (SaleStockImportTime saleStockImportTime : saleStockImportTimes) {
                                    z.or(r -> r
                                            .ge(SaleStock::getSaleTime, RebateDateUtil.getStartOfDayTimestamp(saleStockImportTime.getStartTime()))
                                            .le(SaleStock::getSaleTime, RebateDateUtil.getEndOfDayTimestamp(saleStockImportTime.getEndTime()))
                                            .eq(SaleStock::getTag, userExtend.getClientId())
                                    );
                                    z.or(r -> r.not(x -> x
                                                            .ge(SaleStock::getSaleTime, RebateDateUtil.getStartOfDayTimestamp(saleStockImportTime.getStartTime()))
                                                            .le(SaleStock::getSaleTime, RebateDateUtil.getEndOfDayTimestamp(saleStockImportTime.getEndTime()))
                                                    ).and(zz -> zz.eq(SaleStock::getTag, "").or(o -> o.isNull(SaleStock::getTag)))
                                                    .eq(SaleStock::getTest, 0)
                                    );
                                }
                            });
                        });
                    }
                }
            });
        }

        lambdaQueryWrapper.eq(SaleStock::getType, type);
        if (Objects.equals(type, SaleStockTypeEnum.CD.getType())) {
            lambdaQueryWrapper.in(SaleStock::getStoCode, "100");
        } else if (Objects.equals(type, SaleStockTypeEnum.PD.getType())) {
            lambdaQueryWrapper.notIn(SaleStock::getStoCode, "101", "114", "100");
            lambdaQueryWrapper.eq(StringUtils.isNotBlank(queryStockRequest.getStoreCode()), SaleStock::getStoCode, queryStockRequest.getStoreCode());
        } else {
            lambdaQueryWrapper.notIn(SaleStock::getStoCode, "100", "101", "114");
            lambdaQueryWrapper.eq(StringUtils.isNotBlank(queryStockRequest.getStoreCode()), SaleStock::getStoCode, queryStockRequest.getStoreCode());
        }
        return lambdaQueryWrapper;
    }


    @PostResource(name = "库存列表-开放平台接口", path = "/inventory", requiredLogin = true, requiredPermission = true)
    @ApiOperation("库存列表-开放平台接口")
    public ResponseData<PageResult<KucunVO>> stockListOpen(@RequestBody QueryWarehouseStockRequest
                                                                   queryStockRequest, @RequestHeader("clientId") String clientId, @RequestHeader("token") String token) {
        UserExtend userExtend = checkToken(token, clientId);
        Long userId = userExtend.getUserId();

        List<UserRelation> userRelations = userRelationService.list(Wrappers.<UserRelation>lambdaQuery().in(UserRelation::getUserId, userId));
        if (CollectionUtils.isEmpty(userRelations)) {
            return new SuccessResponseData<>(new PageResult());
        }

        return getStockData(queryStockRequest, userId, "goods", "supplier");
    }

    @PostResource(name = "厂家进销存列表", path = "/sale-stock", requiredLogin = false, requiredPermission = false)
    @ApiOperation("厂家进销存列表")
    public ResponseData<PageResult<SaleStockVO>> listVenderOpen(@RequestBody QueryStockRequest
                                                                        queryStockRequest, @RequestHeader("clientId") String clientId, @RequestHeader("token") String token) {
        log.info("解析到一条数据:{}", JSON.toJSONString(queryStockRequest));

        UserExtend userExtend = checkToken(token, clientId);
        Long userId = userExtend.getUserId();

        List<UserRelation> userRelations = userRelationService.list(Wrappers.<UserRelation>lambdaQuery().in(UserRelation::getUserId, userId));
        if (CollectionUtils.isEmpty(userRelations)) {
            return new SuccessResponseData<>(new PageResult());
        }
        return getPageResultSuccessResponseData(queryStockRequest, null, userId, null);
    }

    private UserExtend checkToken(String token, String clientId) {
        UserExtend userExtend = userExtendService.getOne(Wrappers.<UserExtend>lambdaQuery().eq(UserExtend::getClientId, clientId));
        if (Objects.isNull(userExtend)) {
            throw new BusinessException(BusinessExceptionEnum.BUSINESS_ILLEGAL_CLIENTID);
        }
        String oldToken = userExtend.getToken();
        if (!Objects.equals(oldToken, token)) {
            throw new BusinessException(BusinessExceptionEnum.BUSINESS_ILLEGAL_TOKEN);
        }
        Long expirationTime = userExtend.getExpirationTime();

        if (expirationTime < System.currentTimeMillis()) {
            throw new BusinessException(BusinessExceptionEnum.BUSINESS_EXPIRED_TOKEN);
        }
        return userExtend;
    }


    @ResponseBody
    @PostResource(name = "进销存数据导入", path = "/upload", requiredLogin = true, requiredPermission = true)
    @ApiOperation("供应商导入")
    @BusinessLog
    public ResponseData<String> upload(MultipartFile file) throws IOException {
        ArrayList<String> errorList = Lists.newArrayList();
        EasyExcel.read(file.getInputStream(), StockExcelVO.class, new StockListener(saleStockService, supplierService, goodsService, errorList)).sheet().doRead();
        return new SuccessResponseData<>(String.join(",", errorList));
    }


    @ResponseBody
    @PostResource(name = "进销存数据导入", path = "/upload/as/supplier", requiredLogin = true, requiredPermission = true)
    @ApiOperation("供应商导入")
    @BusinessLog
    public ResponseData<String> uploadAsSupplier(MultipartFile file) throws IOException {
        ArrayList<String> errorList = Lists.newArrayList();
//        EasyExcel.read(file.getInputStream(), ASStocakExcelVO.class, new StockAsListener(saleStockService, supplierService, goodsService, errorList)).sheet().doRead();
        EasyExcel.read(file.getInputStream(), APostsSaleExcelVO.class, new StockAsPosSaleListener(saleStockService, supplierService, goodsService, errorList, gaiaBatchInfoService)).sheet().doRead();
        return new SuccessResponseData<>(String.join(",", errorList));
    }


    @ResponseBody
    @PostResource(name = "进销存删除", path = "/delete", requiredLogin = true, requiredPermission = true)
    @ApiOperation("进销存删除")
    @BusinessLog
    public ResponseData<Boolean> delete(String id) throws IOException {
        saleStockService.removeById(id);
        return new SuccessResponseData<>(true);
    }


    @PostResource(name = "销售列表", path = "/sale/list", requiredLogin = true, requiredPermission = true)
    @ApiOperation("销售列表")
    public ResponseData<PageResult<SaleVO>> saleList(@RequestBody QueryStockRequest queryStockRequest) {
        log.info("解析到一条数据:{}", JSON.toJSONString(queryStockRequest));

        Page page = new Page<>();
        page.setCurrent(queryStockRequest.getPageNo());
        page.setSize(queryStockRequest.getPageSize());
        Long saleTimeBegin = queryStockRequest.getSaleTimeBegin();
        Long saleTimeEnd = queryStockRequest.getSaleTimeEnd();
        String goodsId = queryStockRequest.getGoodsId();
        String storeCode = queryStockRequest.getStoreCode();

        LambdaQueryWrapper<SaleStock> lambdaQueryWrapper = Wrappers.<SaleStock>lambdaQuery().eq(StringUtils.isNotBlank(goodsId), SaleStock::getGoodsId, goodsId).eq(SaleStock::getType, "sale").eq(SaleStock::getTag, "import-test-sale-2023")
//                .eq(SaleStock::getTest, 0)
                .in(StringUtils.isNotBlank(storeCode), SaleStock::getStoCode, storeCode).ge(Objects.nonNull(saleTimeBegin), SaleStock::getSaleTime, saleTimeBegin).le(Objects.nonNull(saleTimeEnd), SaleStock::getSaleTime, saleTimeEnd);

//        lambdaQueryWrapper.and(r -> r.ge(SaleStock::getSaleTime, 1704038400000L)
//                .or(z -> z.eq(SaleStock::getTag, "import-test-sale-2023")
//                        .le(SaleStock::getSaleTime, 1704038400000L))
//        );
        page = saleStockService.page(page, lambdaQueryWrapper);
        List<SaleStock> records = page.getRecords();
        fillInfoMabi(records, page);
        return new SuccessResponseData<>(PageResultFactory.createPageResult(page));
    }


    @PostResource(name = "销售列表统计", path = "/sale/list/sum", requiredLogin = true, requiredPermission = true)
    @ApiOperation("销售列表统计")
    public ResponseData<SaleSumVO> sum(@RequestBody QueryStockRequest queryStockRequest) {
        log.info("解析到一条数据:{}", JSON.toJSONString(queryStockRequest));

        Long saleTimeBegin = queryStockRequest.getSaleTimeBegin();
        Long saleTimeEnd = queryStockRequest.getSaleTimeEnd();
        String goodsId = queryStockRequest.getGoodsId();
        String storeCode = queryStockRequest.getStoreCode();

        QueryWrapper<SaleStock> lambdaQueryWrapper = Wrappers.<SaleStock>query().select("sum(num) as num", "sum(amount_receivable) as amount_receivable", "sum(receivable_price) as receivable_price").eq(StringUtils.isNotBlank(goodsId), "goods_id", goodsId).eq("type", "sale").eq("tag", "import-test-sale-2023")

//                .eq("test", 0)
                .eq(StringUtils.isNotBlank(storeCode), "sto_code", storeCode).ge(Objects.nonNull(saleTimeBegin), "sale_time", saleTimeBegin).le(Objects.nonNull(saleTimeEnd), "sale_time", saleTimeEnd);

//        lambdaQueryWrapper.and(r -> r.ge("sale_time", 1704038400000L)
//                .or(z -> z.eq("tag", "import-test-sale-2023")
//                        .le("sale_time", 1704038400000L)
//                )
//        );
        SaleStock one = saleStockService.getOne(lambdaQueryWrapper);
        SaleSumVO saleSumVO = new SaleSumVO();
        if (Objects.nonNull(one)) {
            BigDecimal amountReceivable = one.getAmountReceivable();
            if (Objects.nonNull(amountReceivable)) {
                saleSumVO.setAmountReceivable(amountReceivable.setScale(4, BigDecimal.ROUND_HALF_UP));
            } else {
                saleSumVO.setAmountReceivable(new BigDecimal(0));
            }

            saleSumVO.setNum(one.getNum());
            Double receivablePrice = one.getReceivablePrice();
            if (Objects.nonNull(receivablePrice)) {
                saleSumVO.setReceivablePrice(new BigDecimal(receivablePrice).setScale(4, BigDecimal.ROUND_HALF_UP));
            } else {
                saleSumVO.setReceivablePrice(new BigDecimal(0));
            }
            return new SuccessResponseData<>(saleSumVO);
        } else {
            saleSumVO.setReceivablePrice(new BigDecimal(0));
            saleSumVO.setNum(0);
            saleSumVO.setReceivablePrice(new BigDecimal(0));
        }

        return new SuccessResponseData<>(saleSumVO);
    }

    private void fillInfoMabi(List<SaleStock> records, Page page) {
        if (CollectionUtils.isNotEmpty(records)) {
            List<String> supplierIdList = records.stream().map(SaleStock::getSupplierId).collect(Collectors.toList());
            List<String> goodsIdList = records.stream().map(SaleStock::getGoodsId).collect(Collectors.toList());
            List<String> storeCodeList = records.stream().map(SaleStock::getStoCode).collect(Collectors.toList());
            List<String> batchNoList = records.stream().map(SaleStock::getBatchNo).collect(Collectors.toList());

            Map<String, Supplier> supplierMap = supplierService.listByIds(supplierIdList).stream().collect(Collectors.toMap(Supplier::getSupplierId, Function.identity()));
            Map<String, Goods> goodsMap = goodsService.listByIds(goodsIdList).stream().collect(Collectors.toMap(Goods::getGoodsId, Function.identity()));
            Map<String, Store> storeMap = storeService.list(Wrappers.<Store>lambdaQuery().in(Store::getStoreCode, storeCodeList)).stream().collect(Collectors.toMap(Store::getStoreCode, Function.identity()));
            Map<String, GaiaBatchInfo> batchInfoMap = gaiaBatchInfoService.list(Wrappers.<GaiaBatchInfo>lambdaQuery().in(GaiaBatchInfo::getBatBatch, batchNoList)).stream().collect(Collectors.toMap(GaiaBatchInfo::getBatBatch, Function.identity()));
            List<String> proCodeList = goodsMap.values().stream().map(Goods::getCommodityCode).collect(Collectors.toList());
            Map<String, GaiaProductBusiness> gaiaProductBusinessMap = gaiaProductBusinessService.list(Wrappers.<GaiaProductBusiness>lambdaQuery().in(GaiaProductBusiness::getProSelfCode, proCodeList)).stream().collect(Collectors.toMap(GaiaProductBusiness::getProSelfCode, Function.identity()));

            List<SaleVO> collect = records.stream().map(r -> {
                GaiaBatchInfo gaiaBatchInfo = batchInfoMap.get(r.getBatchNo());
                Goods goods = goodsMap.get(r.getGoodsId());
                SaleVO conver = saleStockConverter.converSaleVo(r, goods, supplierMap.get(r.getSupplierId()), gaiaBatchInfo);
                if (Objects.nonNull(goods)) {
                    GaiaProductBusiness gaiaProductBusiness = gaiaProductBusinessMap.get(goods.getCommodityCode());
                    if (Objects.nonNull(gaiaProductBusiness)) {
                        conver.setProRegisterNo(gaiaProductBusiness.getProRegisterNo());
                        conver.setProBasicCode(gaiaProductBusiness.getProBasicCode());
                        conver.setProHyj(new BigDecimal(gaiaProductBusiness.getProHyj()).setScale(4, BigDecimal.ROUND_HALF_UP));
                    }
                }

                Store store = storeMap.get(r.getStoCode());
                if (Objects.nonNull(store)) {
                    conver.setStoreName(store.getStoreName());
                }
                if (Objects.nonNull(gaiaBatchInfo)) {
                    conver.setPrice(gaiaBatchInfo.getBatPoPrice());
                }
                conver.setTest(Objects.isNull(r.getTest()) ? 0 : r.getTest());
                String extInfo = r.getExtInfo();
                String tag = r.getTag();
                if (StringUtils.equals(tag, "import-test-sale-2023")) {
                    Year23SaleExcelVO year23SaleExcelVO = JSON.parseObject(extInfo, Year23SaleExcelVO.class);
                    conver.setMemberCardNo(year23SaleExcelVO.getMemberCardNo());
                    conver.setMemberName(year23SaleExcelVO.getMemberName());
                    conver.setMemberCardType(year23SaleExcelVO.getMemberCardType());
                    conver.setSalesmanCode(year23SaleExcelVO.getSalesmanCode());
                    conver.setSalesmanName(year23SaleExcelVO.getSalesmanName());
                    conver.setCashierCode(year23SaleExcelVO.getCashierCode());
                    conver.setCashierName(year23SaleExcelVO.getCashierName());
                    conver.setAmountReceivable(year23SaleExcelVO.getAmountReceivable());
//                    String expiryDays = year23SaleExcelVO.getExpiryDays();
//                    if (Objects.nonNull(expiryDays)) {
//                        conver.setBatExpireDateNum(Integer.parseInt(expiryDays));
//                    }
//                    conver.setBatExpireDate(year23SaleExcelVO.getExpiryDate());
                    conver.setBillNo(year23SaleExcelVO.getSaleNo());
//                    conver.setBatchNo(year23SaleExcelVO.getBatchNo());
                } else {
                    String billNo = r.getBillNo();
                    List<GaiaSdSaleD> gaiaSdSaleDS = gaiaSdSaleDMapper.selectList(Wrappers.<GaiaSdSaleD>lambdaQuery().eq(GaiaSdSaleD::getGssdBillNo, billNo));
                    if (CollectionUtils.isNotEmpty(gaiaSdSaleDS)) {
                        GaiaSdSaleD gaiaSdSaleD = gaiaSdSaleDS.get(0);
                        String gssdSalerId = gaiaSdSaleD.getGssdSalerId();
                        List<GaiaUserData> gaiaUserDataList = gaiaUserDataMapper.selectList(Wrappers.<GaiaUserData>lambdaQuery().eq(GaiaUserData::getUserId, gssdSalerId));
                        if (CollectionUtils.isNotEmpty(gaiaUserDataList)) {
                            GaiaUserData gaiaUserData1 = gaiaUserDataList.get(0);
                            conver.setCashier(gaiaUserData1.getUserNam());
                            conver.setCashierCode(gssdSalerId);
                            conver.setSalesmanCode(gssdSalerId);
                            conver.setSalesmanName(gaiaUserData1.getUserNam());
                            conver.setCashierName(gaiaUserData1.getUserNam());
                        }
                    }
                }
                return conver;
            }).collect(Collectors.toList());
            page.setRecords(collect);
        }
    }


    /**
     * 获取我的配置
     */
    public static List<String> getMailTo() {
        String sysConfigValueWithDefault = ConfigContext.me().getSysConfigValueWithDefault("report.mail.to", String.class, "");
        return Arrays.stream(sysConfigValueWithDefault.split(",")).collect(Collectors.toList());
    }


}
